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

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

Why doesn\'

19条回答
  •  盖世英雄少女心
    2020-11-22 12:21

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

提交回复
热议问题