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

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

Why doesn\'

19条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 12:23

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

提交回复
热议问题