How can I get the ID of an element using jQuery?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么没有上述工作,我该怎么做?
The jQuery way:
$('#test').attr('id')
In your example:
<div id="test"></div>
$(document).ready(function() {
alert($('#test').attr('id'));
});
Or through the DOM:
$('#test').get(0).id;
or even :
$('#test')[0].id;
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 functionality
an alternative for DOM selector in jquery is
$('#test').prop('id')
which is different from .attr()
and $('#test').prop('foo')
grabs the specified DOM foo
property, while $('#test').attr('foo')
grabs the specified HTML foo
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:
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})
id
is a property of an html Element
. However, when you write $("#something")
, it returns a jQuery object that wraps the matching DOM element(s). To get the first matching 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")
链接地址: http://www.djcxy.com/p/2360.html
上一篇: 滚动后检查元素是否可见
下一篇: 我如何使用jQuery获取元素的ID?