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

后端 未结 19 2616
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:57

Why doesn\'

19条回答
  •  死守一世寂寞
    2020-11-22 12:27

    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!
    

提交回复
热议问题