Search code examples
javascriptjquerynullundefinedchain

addClass(undefined) vs. addClass(null)


Sometimes I'd like to add class in chain, under some condition. What value would be semantically most appropriate to add no class?

Example:

$(".element").doSomething().addClass(condition ? "special-class" : undefined).doSomethingElse();

Or:

$(".element").doSomething().addClass(condition ? "special-class" : null).doSomethingElse();

Solution

  • Use $.toggleClass() instead:

    $(".element").doSomething().toggleClass("special-class",condition).doSomethingElse();
    

    As ruakh mentioned it, there is a difference. If condition is falsy, it will actually remove the class if it was present before. With your logic, the class can only be added, not removed.