Is it possible to obtain the id of an element (div, input etc) using jQuery and how?
+6
A:
See Attributes/attr
Simple example:
alert($('div.someclass').attr('id'));
If there is more than one div with the class someclass
(that is to say, the selector returns more than one element), you can get them all by looping through the elements using each, and pushing the ids into an array for example:
var ids = [];
$('div.someclass').each(function() {
ids.push($(this).attr('id'));
});
Just to go a little further, you can use attribute filters (in this case attributeHas
) to pick out only those elements that have ids, e.g.:
var ids = [];
$('div[id]').each(function() {
ids.push($(this).attr('id'));
});
and finally, instead of using each, you can use map( callback )
which provides a neater way of doing the above:
var ids = $('div[id]').map(function(index, domElement) {
return $(domElement).attr('id');
}).get();
alert(ids.join(","));
karim79
2009-09-21 16:47:43
+1 for the most complete answer at the time. I love jquery!
Redbeard 0x0A
2009-09-21 16:51:15
Don't manually push... We have $.fn.map() for that.
J-P
2009-09-21 17:43:25
@J-P thanks, I've thrown it in.
karim79
2009-09-22 02:38:47
+2
A:
$('elementselector').attr('id');
You would need to pick a proper selector to make sure you select the element of interest.
womp
2009-09-21 16:47:45
If you already have the element, as in your example, it'd be clearer and faster to just do element.id
TM
2009-09-21 16:50:00