I want to add an active class to the <li>
that an ID is in, for example:
<li><a href="" id="foo">text</a></li>
How can I add a class to the <li>
that #foo
is in?
I want to add an active class to the <li>
that an ID is in, for example:
<li><a href="" id="foo">text</a></li>
How can I add a class to the <li>
that #foo
is in?
$('#foo').parent('li').addClass("yourclass")
$("#foo").closest("li").addClass("bar");
タグが他の要素でラップされて<a>
いる可能性があり、の直接の子ではない場合<li>
、は機能しparent('li')
ません。
HTML
<ul>
<li><div><a id="foo">Foo</a></div></li>
<li><div><a id="bar">Bar</a></div></li>
</ul>
JS
$("#foo").closest("li").addClass("foo"); // this will correctly grab the li
$("#bar").parent("li").addClass("bar"); // this will grab nothing
$('#foo').parent('li').addClass('active');
$("li").has("#foo").addClass("yourclass")
$('a[id]').closest('li').addClass('active');
まず、ID セレクターfoo
を使用して ID を持つ要素を選択します。次に、 を使用してその要素の親を選択します。最も近い親のみが検出されるようにするために使用します。最後に、 を使用してクラスを要素に追加します。.parents
<li>
.eq(0)
addClass
<li>
ID を持つ要素がいくつかの要素の下にネストされている場合でも、親を使用しているため、それ は引き続き選択されます。foo
<li>
$("#foo").parents("li").eq(0).addClass("bar");