admin管理员组

文章数量:1332107

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.

Share Improve this question edited Nov 7, 2018 at 19:18 JustLearning 3,3323 gold badges36 silver badges57 bronze badges asked Aug 18, 2011 at 13:59 scottoscotto 891 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Here'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