difference between toggleclass and addclass

15,374

Solution 1

addClass does just that, adds the class to the element.

toggleClass on the other hand does THAT, toggles the class, removing it if it's there, otherwise adding it, but optionally taking a boolean value (true/false) to determine if the object should be added (true) or removed (false).

toggleClass probably wasn't working for you in the instances where this.clicked was false, which is expected behavior. The argument you're passing in addClass has no effect, since it ALWAYS adds the class.

Conclusion:

Use toggleClass for toggling classes, use addClass for adding classes.

Solution 2

If addClass is working for you, then you should stick with it. The methods are meant for different purposes. addClass ensures that a particular class is present on an element, while toggleClass adds the class if it isn't there and removes it if it is.

Check out the API reference for the full explanation of each method:

Solution 3

There's no need to pass a second argument to .addClass() - it will always add the class.

If that's the behaviour you want, that's the right method.

Solution 4

Depends really. If you don't plan on removing the class, I'd stick with addClass. Naturally, toggleClass allows you to toggle classes.

Share:
15,374
czuroski
Author by

czuroski

MCSD .Net Framework 4.5 | Web Applications MCTS: MOSS 2007 Setup and Administration

Updated on June 12, 2022

Comments

  • czuroski
    czuroski about 2 years

    I am working with jquery and attempting to add a class to a table on the selection of that table row.

    I was initially using the following code -

    $(this).parents("tr").toggleClass("over", this.clicked);            
    

    For some reason, that wasn't working in only some instances where there was already a class assigned. Before I went too crazy with any troubleshooting, I changed it to the following -

    $(this).parents("tr").addClass("over", this.clicked);           
    

    This new option appears to be working fine.

    My question is whether one option above is better than the other.....Should I be using toggleClass instead of addClass, or is addClass sufficient?

    thanks for any thoughts.

  • czuroski
    czuroski over 12 years
    I am actually going through and removing the particular class for all rows in the table before I add it onto the row that is selected. Therefore, I think that just addClass will accomplish exactly what I need. Thanks
  • czuroski
    czuroski over 12 years
    Thanks for mentioning that the second argument is unnecessary... I removed it and it worked fine.