Vertisan
Vertisan

Reputation: 738

jQuery - if parent has not class

I want to create auto-add class to DIV, so I do:

$( '.navigation' ).find( 'li.active' ).parents( 'li' ).addClass( 'active' );

It's works great! But now I need to 'ignore' parents if has, eg. 'dropdown-toggle' so I modified this for:

$( '.navigation' ).find( 'li.active' ).parents( 'li:not(.dropdown-toggle)' ).addClass( 'active' );

But that's not working - where is my bad?

Upvotes: 2

Views: 271

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Try to use parents() with :not like :

$('.navigation li.active').parents('li:not(".dropdown-toggle")').addClass('active');

Hope this helps.

$('.navigation li.active').parents('li:not(".dropdown-toggle")').addClass('active');
.active{
  background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='navigation'>
  <li>Water</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li class='active'>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
  <li class='dropdown-toggle'>Coffee (Has dropdown-toggle class)
    <ul>
      <li>Black Coffee</li>
      <li class='active'>Cream Coffee</li>
    </ul>
  </li>
</ul>

Upvotes: 1

Related Questions