<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.
How to use:
Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:
$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");
Above answers are great, but as jquery evolves.. so you can also do:
$('#test')
returns a jQuery object, so you can't use simplyobject.id
to get itsId
you need to use
$('#test').attr('id')
, which returns your requiredID
of the elementThis can also be done as follows ,
$('#test').get(0).id
which is equal todocument.getElementById('test').id
The jQuery way:
In your example:
Or through the DOM:
or even :
and reason behind usage of
$('#test').get(0)
in JQuery or even$('#test')[0]
is that$('#test')
is a JQuery selector and returns an array() of results not a single element by its default functionalityan alternative for DOM selector in jquery is
which is different from
.attr()
and$('#test').prop('foo')
grabs the specified DOMfoo
property, while$('#test').attr('foo')
grabs the specified HTMLfoo
attribute and you can find more details about differences here.$('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:Or, if you're willing to get a little grittier, you can avoid the wrapper and use the
.map
shortcut.