admin管理员组文章数量:1335356
I thought that the closest()
function would do this for me, but seemingly not. I have the following markup and I want to add a class
to all parent anchors with the class trigger:
<ul>
<li class="selected">
<a class="trigger" href=""></a>
<a href=""></a>
<ul>
<li class="selected">
<a class="trigger" href=""></a>
<a href="" id = "my_target"></a>
</li>
</ul>
</li>
</ul>
I want to select my target - in this example, the deepest anchor, then add a class
to each a.trigger
in its ascendants. What would be the best way to do this? Thanks.
I thought that the closest()
function would do this for me, but seemingly not. I have the following markup and I want to add a class
to all parent anchors with the class trigger:
<ul>
<li class="selected">
<a class="trigger" href=""></a>
<a href=""></a>
<ul>
<li class="selected">
<a class="trigger" href=""></a>
<a href="" id = "my_target"></a>
</li>
</ul>
</li>
</ul>
I want to select my target - in this example, the deepest anchor, then add a class
to each a.trigger
in its ascendants. What would be the best way to do this? Thanks.
3 Answers
Reset to default 3Here's an example using a bination of jQuery.parents()
(to get the containing <li>
tags) and then jQuery.children()
to get the <a>
tags with a class of trigger:
$(document).ready( function() {
$('#my_target').click( function(e) {
$(this).parents('li.selected').children('a.trigger').addClass('myclass');
e.preventDefault();
});
});
jsfiddle example
EDIT:
Note $().parents()
traverses all the way up the tree, but $().children()
only traverses down one level. To gather all descendents of an element use $().find()
.
You want to use
$('#my_target').parents('a.trigger');
Using the .parents method (which traverses all the way up the DOM tree, rather than .parent, which only traverses one level up.
parents
Is used for traversing up.
I believe this should work:
$('#my_target').parents('.trigger').addClass('myclass');
However for siblings you'll need to use siblings
instead of parents
For example the anchor
tag that is with the #my_target
anchor is considered a sibling.
本文标签: javascriptjquerytraverse up tree and find elements with specified classStack Overflow
版权声明:本文标题:javascript - jquery - traverse up tree and find elements with specified class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742258408a2442055.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论