How can I get the ID of an element using jQuery?

2018-12-31 23:09发布

<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

Why doesn't the above work, and how should I do this?

17条回答
浪荡孟婆
2楼-- · 2018-12-31 23:42

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.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

$('.classname').id();

$('#elementId').id();
查看更多
孤独寂梦人
3楼-- · 2018-12-31 23:42

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");

查看更多
余生无你
4楼-- · 2018-12-31 23:43

Above answers are great, but as jquery evolves.. so you can also do:

var myId = $("#test").prop("id");
查看更多
忆尘夕之涩
5楼-- · 2018-12-31 23:43

$('#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

查看更多
君临天下
6楼-- · 2018-12-31 23:46

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.

查看更多
与君花间醉酒
7楼-- · 2018-12-31 23:49

$('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})
查看更多
登录 后发表回答