0

I have problem with remove the attribute class="active" in tag li.

I have 2 class in tag <li>.

One is: active,

another one is: dropdown

but i just want to remove the previous class="active" and add this to the tag <li> when I clicked it. But when I remove, the class="dropdown" also removed.

I know my code have problem but I dont know how to fix it.

Can anybody help me :)

Sorry, because my english not good :)

HTML

<ul class="nav nav-justified">
     <li class="active"><a href="#">Home</a></li>
     <li><a href="#">Projects</a></li>
     <li><a href="#">Services</a></li>
     <li class="dropdown">
         <a class="dropdown-toggle" data-toggle="dropdown" href="#">
              Dropdown
              <span class="caret"></span>
         </a>
         <ul class="dropdown-menu" role="menu">
             <li>Hoai Thy</li>
             <li>My Huyen</li>
         </ul>
     </li>
     <li><a href="#">About</a></li>
     <li><a href="#">Contact</a></li>
</ul>

Javascript

$(document).ready(function(){
$('.dropdown-toggle').dropdown()
    $(".nav-justified li").each(function(){
    $(this).click(function(){
        $(".nav-justified li").removeAttr();
        $(this).attr("class","active");
     });
   });
});

4 Answers 4

3

An answer based on toggleClass has claready been posted. Alterntivate is to remove and add classes as you are trying to do but in jQuery do that via removeClass and addClass, not via attr. There could be other (pure presentation) classes that you want to leave unaltered).

$(".nav-justified li").click(function(){
   $(".nav-justified li").removeClass('active');
   $(this).addClass("active");
});

Also, you don't need the .each() - .click(function(){}) binds the event to all elements in the collection

Sign up to request clarification or add additional context in comments.

1 Comment

Its complete answer. +1 for proper event binding
1

Use toggleClass() instead of removing attribute and adding the attribute again:

$(".nav-justified li").toggleClass('active');

And removeAttr() method won't remove the class name but it removes the whole attribute.

Comments

0

Use .removeClass() to remove class.also use .addClass() to add class active.Try this:

 $(this).click(function(){
    $(".nav-justified li.active").removeClass('active');
    $(this).addClass("active");
});

1 Comment

You should also use addClass() instead of attr() to set the class
0

This will Work for you.

    $(".nav-justified li").each(function(){
        $(this).toggleClass('active')
     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.