views:

62

answers:

5
<div id="test"></div>

$(document).ready(function() {
    alert($('#test').id);
});  

Can someone please explain to me why the above doesn't work, and tell me how I can get the ID of a jQuery element that has been passed into a function.

+5  A: 

The jQuery way:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

Or through the DOM:

$('#test').get(0).id;
streetpc
+7  A: 

$('selector').attr('id') will return the id of the first matched element. Reference.

If your matched set contains more than one element, you can use the conventional .each iterator to return an array containing each of the ids:

var retval = []
$('selector').each(function(){
  retval.push($(this).attr('id'))
})
return retval

Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map shortcut.

return $('.selector').map(function(index,dom){return dom.id})
Steven Xu
@Shawn Steward: I'm not sure about this. At least with this particular selector, jQuery calls `document.getElementById`, which only returns one DOM element. The issue here is that jQuery `$('selector')` doesn't return a DOM element or a set of DOM elements; it returns a jQuery object (which happens to refer to one DOM element as well as a bunch of other metadata), for which `.id` is not a property.
Steven Xu
@Shawn, nope . The OP code does not work because the $(..) returns a jQUery object which has no ID property. `#test` is an ID and should in any case only return a single object (*since ID **should** be unique*)
Gaby
Thanks guys, yeah I was mistaken. Going to delete the comment so it doesn't confuse anybody.
Shawn Steward
+1  A: 

$('#test') returns a jQuery object, so you can't use simply object.id to get its Id

you need to use $('#test').attr('id'), which returns your required ID of the element

This can also be done as follows ,

$('#test').get(0).id which is equal to document.getElementById('test').id

Ninja Dude
.. and also `$('#test')[0].id` which is the same as `.get(0)`
Gaby
Thanks for letting me know. Have a Nice Day!!
Ninja Dude
+1  A: 

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the DOM element. To get the native DOM element back, call get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

$("#test").get(0).id

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")
Anurag
A: 

.id is not a valid jquery function. You need to use the .attr() function to access attributes an element possesses. You can use .attr() to both change an attribute value by specifying two parameters, or get the value by specifying one.

http://api.jquery.com/attr/

Joey C.