user1817708
user1817708

Reputation: 45

JQuery Add Class To Parent Object

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.

Upvotes: 3

Views: 15937

Answers (3)

Sushanth --
Sushanth --

Reputation: 55740

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

Upvotes: 3

Jai
Jai

Reputation: 74738

try with this one:

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

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

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

You can do simpler :

 $('ul.top li.parent:has(.active)').addClass('active');

Upvotes: 0

Related Questions