I know you use the attr method to get the attribute for the first item in a matched set, e.g. $('input').attr('name') gives you the name attribute for the first matched input element.
But how do I get the attribute directly from an HTML element, e.g. $('input')[0]? I’d like to do something like $('input')[0].attr('name') but that doesn’t work, as attr is only a method of jQuery matched sets, not the items within matched sets.
(By the way, this has come up because I’d like to pass items from within a matched set to a function, and be able to see the attributes of that item within the function.)
If by
[0]you simply want to get a specific element from a matched set, usedeq():Will get the
nameattribute of the first element in the set returned by theselector. Of course, the the0can be replaced by the index number of any element returned by that selector.Similarly, you could use the
:eq()selector:Or, if
selectoris a variable:As Alnitak notes, in the comments below:
Of course, you could, for certain names, or properties, just fall back to the DOM methods:
Or:
References:
:eq().eq().