views:

207

answers:

3

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
+1 for the most complete answer at the time. I love jquery!
Redbeard 0x0A
Don't manually push... We have $.fn.map() for that.
J-P
@J-P thanks, I've thrown it in.
karim79
+2  A: 
$('elementselector').attr('id');

You would need to pick a proper selector to make sure you select the element of interest.

womp
+1  A: 
$(element).attr('id')
Lukasz Lysik
If you already have the element, as in your example, it'd be clearer and faster to just do element.id
TM