結論
parentで親要素は複数取れてしまう。なのでclosestを使う。
各メソッドの違い
コード例
<!-- test.html -->
<div class="grandparent">
<div class="parent1">
<div class="child1">Child 1</div>
</div>
<div class="parent2">
<div class="child2">Child 2</div>
</div>
</div>
parent()
parent()メソッドは、選択した要素の直近の親要素を1つだけ取得する。
// parent()の例
// 直近の親要素を取得
console.log($('.child1').parent().attr('class'));
// 出力: "parent1"
注意点:複数の階層をさかのぼりたい場合は、メソッドチェーンを使用する。
console.log($('.child1').parent().parent().attr('class'); // 2階層上の親要素を取得
// 出力:"grandparent"
parents()
parents()メソッドは、選択した要素のすべての親要素を取得する。
// parents()の例
$('.child1').parents().each(function() {
console.log($(this).attr('class'));
});
// 出力:
// "parent1"
// "grandparent"
// undefined (body要素)
// undefined (html要素)
htmlまで取得できるので使うときはセレクタで指定する
// parents()でセレクタ指定の例
console.log($('.child1').parents('.grandparent').attr('class'));
// 出力: "grandparent"
closest()
closest()メソッドは、選択した要素自身を含む最も近い親要素を1つだけ取得する。
注意点:セレクタの指定が必須。また、条件に合致すれば選択した要素自身が返される場合もある。
// closest()の例
console.log($('.child1').closest('.grandparent').attr('class'));
// 出力: "grandparent"
// closest()で自身を含む例
console.log($('.child1').closest('.child1').text());
// 出力: "Child 1"
まとめ
- parent():直近の親要素を1つ取得
- parents():すべての親要素を取得(セレクタで絞り込み可能)
- closest():最も近い特定の親要素を1つ取得(自身を含む)