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

2018-12-31 23:35发布

问题:

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

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

回答1:

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.



回答2:

$(\'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})


回答3:

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


回答4:

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

var myId = $(\"#test\").prop(\"id\");


回答5:

$.fn.extend({
    id : function() {
        return this.attr(\'id\');
    }
});

alert( $(\'#element\').id() );

Some checking code required of course, but easily implemented!



回答6:

.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/



回答7:

If you want to get an ID of an element, let\'s say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:

 $(\'.your-selector\').click(function(){
       var id = $(this).attr(\'id\');
 });


回答8:

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



回答9:

Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype\'s. I put this in a Helper file that is loaded after the JQuery library, hence the check for window.jQuery

if (window.jQuery) {
    $.prototype.id = function () {
        if (this.length > 1) {
            var val = [];
            this.each(function (idx, el) {
                val.push($(el).id());
            });
            return val;
        } else {
            return this.attr(\'id\');
        }
    }
}

It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.

Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.



回答10:

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


回答11:

$(\'#test\').attr(\'id\') In your example:

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

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


回答12:

This is an old question, but as of 2015 this may actually work:

$(\'#test\').id;

And you can also make assignments:

$(\'#test\').id = \"abc\";

As long as you define the following JQuery plugin:

Object.defineProperty($.fn, \'id\', {
    get: function () { return this.attr(\"id\"); },
    set: function (newValue) { this.attr(\"id\", newValue); }
});

Interestingly, if element is a DOM element, then:

element.id === $(element).id; // Is true!


回答13:

$(\'tagname\').attr(\'id\');

Using above code you can get id.



回答14:

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



回答15:

This can be element id , class , or automatically using even

------------------------
$(this).attr(\'id\');
=========================
------------------------
$(\"a.remove[data-id=\'2\']\").attr(\'id\');
=========================
------------------------
$(\"#abc1\'\").attr(\'id\');
=========================


回答16:

This will finally solve your problems:

lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.

lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the \"like\" buttons.

here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.

<!DOCTYPE html>
<html>
<head>
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\">    </script>
<script>
$(document).ready(function(){
$(\".clshlpbtn\").on(\'click\',function(e){
var id = $(e.target).attr(\'id\');
 alert(\"The id of the button that was clicked: \"+id);
$.post(\"demo_test_post.asp\",
    {
      name: \"Donald Duck\",
      city: \"Duckburg\"
    },
    function(data,status){

    //parsing the data should come here:
    //var obj = jQuery.parseJSON(data);
    //$(\"#\"+id).val(obj.name);
    //etc.

    if (id==\"btnhlp-1\")
       $(\"#\"+id).attr(\"style\",\"color:red\");
    $(\"#\"+id).val(data);
    });
});




});
</script>
</head>
<body>

<input type=\"button\" class=\"clshlpbtn\" id=\"btnhlp-1\" value=\"first btn\">    </input>
<br />
<input type=\"button\" class=\"clshlpbtn\" id=\"btnhlp-2\" value=\"second btn\">    </input>
<br />
<input type=\"button\" class=\"clshlpbtn\" id=\"btnhlp-9\" value=\"ninth btn\">    </input>

</body>
</html>

code was taken from w3schools and changed.



回答17:

Since the id is an attribute, you can get it by using the attr method.