Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - traverse up tree and find elements with specified class

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.

like image 769
scotto Avatar asked Aug 18 '11 13:08

scotto


1 Answers

Here's an example using a combination 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().

like image 130
Mark Biek Avatar answered Sep 23 '22 21:09

Mark Biek