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

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

Why doesn\'

19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 12:30

    The jQuery way:

    $('#test').attr('id')
    

    In your example:

    $(document).ready(function() {
      console.log($('#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.

提交回复
热议问题