hoaithy92
hoaithy92

Reputation: 39

Remove attribute html in Jquery

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");
     });
   });
});

Upvotes: 0

Views: 157

Answers (4)

Adam
Adam

Reputation: 6783

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

Upvotes: 3

Kaushal Khamar
Kaushal Khamar

Reputation: 2123

This will Work for you.

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

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82251

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");
});

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85643

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.

Upvotes: 1

Related Questions