Ghopper21
Ghopper21

Reputation: 10477

With jQuery, how to get the attribute for an HTML element i.e. not the first element of a matched set?

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.)

Upvotes: 0

Views: 1486

Answers (2)

MStodd
MStodd

Reputation: 4746

When you have an actual HTML object, you can still JQuery-ify it by wrapping it in $(element), then have access to attr()

var secondThing = $('input')[1]
foo(secondThing)

function foo(element){
var elem = $(element);
var name = elem.attr('name');

//or
name = element.getAttribute('name')

}

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

If by [0] you simply want to get a specific element from a matched set, used eq():

$(selector).eq(0).attr('name');

Will get the name attribute of the first element in the set returned by the selector. Of course, the the 0 can be replaced by the index number of any element returned by that selector.

Similarly, you could use the :eq() selector:

$('div:eq(0)').attr('name');

Or, if selector is a variable:

$(selector + ':eq(0)').attr('name');

As Alnitak notes, in the comments below:

If you're going to use eq, use .eq(n) rather than :eq(n) so that the browser can use querySelectorAll() - the latter is a jQuery extension.

Of course, you could, for certain names, or properties, just fall back to the DOM methods:

$(selector)[0].name;

Or:

$(selector)[0].getAttribute('name');

References:

Upvotes: 4

Related Questions