<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.
<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.
The jQuery way:
<div id="test"></div>
$(document).ready(function() {
alert($('#test').attr('id'));
});
Or through the DOM:
$('#test').get(0).id;
$('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})
$('#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
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")
.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.