JQuery Add Class To Parent Object

15,832

Solution 1

You can loop over all the li's and add the class to the closest parent ul

$('ul.top li').each(function(){
    var $this = $(this);
    if($this.hasClass('active')){
        $this.closest('li.parent').addClass('active');
    }        
});

Check fiddle

Solution 2

try with this one:

$('li.active').parent().closest('li.parent').addClass('active');

checkout the fiddle: http://jsfiddle.net/FmT52/8/

Share:
15,832
user1817708
Author by

user1817708

Updated on July 31, 2022

Comments

  • user1817708
    user1817708 almost 2 years

    I am trying to add a class of 'active' to a parent list item if one of it's children has the class 'active'.

    Current html:

    <ul class="top">
      <li class="parent"><a href="#">Link1</a>
        <ul class="drop">
          <li class="active"><a href="#">Link1-1</a></li>
          <li><a href="#">Link1-2</a></li>
          <li><a href="#">Link1-3</a></li>
        </ul>
      </li>
      <li><a href="#">Link2</a></li>
      <li class="parent"><a href="#">Link3</a></li>
    </ul>
    

    current JQuery:

    if($('ul.top li ul.drop li').hasClass('active')) {
                $('ul.top li.parent').addClass('active');
        } 
    

    Please see http://jsfiddle.net/FmT52/ to view how far I have got.

    I have managed to half do it but only so far as using Jquery to add the class of 'active' to all top level list items.

    As ever, any help will be greatly appreciated.