Charly
Charly

Reputation: 189

Class is not being added with if statement

I have three navigations and I only want the display the one that has the active class, but i'm not able to achieve this. As you can see the list item is the element that has the active class so i'm targeting the list items and not the ul. Thanks!

$(document).ready(function(){
    if ($('.book ul li').hasClass('active')){
        $(this).addClass('showActiveBook');
    }
});
.book{
    display: none;
}
.showActiveBook{
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="book book1">
   <ul>
      <li>
          <a href="#">Book1</a>
       </li>
   </ul>
</nav>

<nav class="book book2">
  <ul>
     <a href="#">Book 2</a>
     <li class="active"> 
         <ul>
             <li>book2Chapter1</li>
             <li>book2Chapter2</li>
         </ul>
     </li>
  </ul>
</nav>

<nav class="book book3">
  <ul>
      <li>
          <a href="#">Book3</a>
      </li>
  </ul>
</nav>

Upvotes: 0

Views: 39

Answers (2)

Djaouad
Djaouad

Reputation: 22766

You can just get the 'li.active' instead of getting all of them and testing, and you can use parents(2) to get the second parent (the parent nav element):

$(document).ready(function(){
   $('.book ul li.active').parents(2).addClass('showActiveBook');
});
.book{
    display: none;
}
.showActiveBook{
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="book book1">
   <ul>
      <li>
          <a href="#">Book1</a>
       </li>
   </ul>
</nav>

<nav class="book book2">
  <ul>
     <a href="#">Book 2</a>
     <li class="active"> 
         <ul>
             <li>book2Chapter1</li>
             <li>book2Chapter2</li>
         </ul>
     </li>
  </ul>
</nav>

<nav class="book book3">
  <ul>
      <li>
          <a href="#">Book3</a>
      </li>
  </ul>
</nav>

Upvotes: 0

Taplar
Taplar

Reputation: 24965

The usage of this is incorrect. Without proper chaining, the this will reference the document or window. However, in your case you do not need an if statement. Simply find the li that has the class of active, find it's parent book element, and add the class to it.

$(document).ready(function(){
    $('.book ul li.active').closest('.book').addClass('showActiveBook');
});
.book{
    display: none;
}
.showActiveBook{
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="book book1">
   <ul>
      <li>
          <a href="#">Book1</a>
       </li>
   </ul>
</nav>

<nav class="book book2">
  <ul>
     <a href="#">Book 2</a>
     <li class="active"> 
         <ul>
             <li>book2Chapter1</li>
             <li>book2Chapter2</li>
         </ul>
     </li>
  </ul>
</nav>

<nav class="book book3">
  <ul>
      <li>
          <a href="#">Book3</a>
      </li>
  </ul>
</nav>

Upvotes: 1

Related Questions