Jquery - cross a tree and find elements with the specified class

I thought the closer () function would do this for me, but it seems not. I have the following markup, and I want to add the class to all the parent anchors using 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 choose my goal - in this example - the deepest anchor, and then add a class to each a.trigger in my descendants. What would be the best way to do this? Thank.

+5
source share
3 answers

This example uses a combination jQuery.parents()(to get tags <li>) and then jQuery.children()to get tags <a>with a trigger class:

$(document).ready( function() {
    $('#my_target').click( function(e) {
        $(this).parents('li.selected').children('a.trigger').addClass('myclass');
        e.preventDefault();
    });
});

Jsfiddle example

EDIT:

$().parents() , $().children() . , $().find().

+3

$('#my_target').parents('a.trigger');

. parent ( DOM, . parent, .

+2

parents Used to move.

I believe this should work:

$('#my_target').parents('.trigger').addClass('myclass');

However, for brothers and sisters you need to use siblingsinstead of parents For example, the tag anchorthat is with the anchor #my_targetis considered a brother.

0
source

All Articles