jQuery select ancestor

后端 未结 6 1952
清酒与你
清酒与你 2020-12-24 06:44

Is is possible to use jQuery to select an ancestor of an element?

Markup:


      
      
6条回答
  •  隐瞒了意图╮
    2020-12-24 07:05

    Try parent() for the immediate parent element.

    $(".click-me").click(function() {
      var ancestor = $(this).parent();
      alert(ancestor)
    });
    

    Or parents() for all matching ancestor elements.

    $(".click-me").click(function() {
      var ancestors = $(this).parents(".some-ancestor");
      alert(ancestors)
    });
    

    Or closest() for the first closest matching element (either an ancestor or self).

    $(".click-me").click(function() {
      var ancestor = $(this).closest(".some-ancestor");
      alert(ancestor)
    });
    

    The difference between parents() and closest() is subtle but important. closest() will return the current element if it's a match; parents() returns only ancestors. You many not want the possibility of returning the current element. closest() also only returns one element; parents() returns all matching elements.

提交回复
热议问题