jQuery get id of element by searching for it by class

后端 未结 2 533
春和景丽
春和景丽 2020-12-31 11:56

This is my html :

a
相关标签:
2条回答
  • 2020-12-31 12:29

    parentsUntil gets all the parent elements until the one matched by the selector. It does not include the element matched. You're trying to get the id of the intervening div, which is obviously undefined.

    You need to use closest, which goes up the DOM tree until it finds an element matching the selector, then returns only that element:

    var abc = $(this).closest(".head-div").attr("id");
    

    Edit: for extra speed, but less flexibility in the event that you change your markup, you could use the parentNode property:

    var abc = this.parentNode.parentNode.id;
    
    0 讨论(0)
  • 2020-12-31 12:44

    You can use .closest( selector ), for example:

    var abc = $(this).closest(".head-div").attr("id");
    

    http://api.jquery.com/closest/

    .parent( selector ) selects only immediate parent of the element.

    0 讨论(0)
提交回复
热议问题