jQuery 祖先を選択する 質問する

jQuery 祖先を選択する 質問する

jQuery を使用して要素の祖先を選択することは可能ですか?

マークアップ:

<div id="ancestor-1">
    <div>
        <a href="#" class="click-me">Click me</a>
    </div>
</div>
<div id="ancestor-2">
    <div>
        <a href="#" class="click-me">Click me</a>
    </div>
</div>

脚本:

$(".click-me").click(function(){
    // var ancestorId = ???;
    alert(ancestorId)
});

ベストアンサー1

試すparent()直下の親要素に対して。

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

またはparents()一致するすべての祖先要素に対して。

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

またはclosest()最初に最も近い一致する要素 (祖先または自分自身) を検索します。

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

parents()との違いはclosest()微妙ですが重要です。はclosest()、一致する場合は現在の要素を返します。parents()先祖だけ現在の要素を返す可能性は望ましくないかもしれません。closest()また、1 つの要素のみを返します。parents()一致するすべての要素を返します。

おすすめ記事