5

What is the best practice way to conditionally add a class to an element? One option is a if statement, and then add the class. Another option is to add the class or add an empty string as a class. Maybe there are better options? Yea, I know speed is probably not important, but I just wish to know the "professional" way of doing this.

var addClass=1; //or 0
var row=$('#cloneElement')
  .clone(false)
  .removeClass('gone')
  .removeAttr('id')
  .attr('data-id',this.id);

if (addClass) {
  row.addClass('newClass');
}

var addClass=1; //or 0
var row=$('#cloneElement')
  .clone(false)
  .removeClass('gone')
  .removeAttr('id')
  .attr('data-id',this.id)
  .addClass(addClass?'newClass':'');
4
  • Both of these are equivalent. Make sure you always stick with a solution that would make sense for you and your fellow colleagues in 2 weeks time. Commented Dec 1, 2013 at 0:34
  • @bagonyi. I agree with sticking with one solution, thus why I asked the question so I can settle on one. Commented Dec 1, 2013 at 0:35
  • IMHO, sticking with the fluent interface for constructing the object makes for more legible code. That's the objective of method chaining. However the overloaded addClass method may make for a more explicit, readable alternative to the conditional operator. .addClass(function() { var newClass; if (addClass === 1) { newClass = "newClass"; } return newClass || ''; }) This all really comes down to personal preference, and team style, however. None of these is particularly obscure or obfuscated. Commented Dec 1, 2013 at 1:03
  • IMHO chaining frameworks should have .addClass(..., condition) methods ... because a lot of times we do have conditions inside the chain code. API devs take note. Commented Nov 14, 2017 at 11:15

5 Answers 5

4

In case you are using jquery ui you can use toggleClass

row.toggleClass('newClass', addClass)
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks bagonyi. I do use jquery ui, but typically resist using the methods if another solution exists.
If addClass is false and the element already has the newClass class then this will remove it - which is not the functionality that was being asked for.
@MT0 adding a switch to toggleClass will add or remove the class based on the switch being respectively true or false api.jquery.com/toggleclass/#toggleClass-className-state .toggleClass( className, state ) state Type: Boolean A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.
@Hussam The OP's question was: if the toggle is true then add the class (if it is not there already) or if the toggle is false then do nothing - at no point are they removing the class (if it exists). The toggleClass() function will remove the class - which is not what the OP asked for.
@MT0, i guessed it was OP's intention to add/remove the class from OP's last line .addClass(addClass?'newClass':''); which would add newClass or empty string, but maybe he didn't express this entirely.
|
2

In my opinion the first version is better. Probably that conditional is crucial to the correct operation of your page, and it is better to make it very clear and explicit, and not make it too obscure.

One of the most important things about professional code is that it should be readable, whether by your colleagues or by you in a few months.

So I recommend, when in doubt eschew the "clever" solution and instead choose the solution that is most obvious and simple and does not require any extra comments to explain it.

Comments

1

here's a simple function that will conditionally add/remove a class by passing a class name and boolean

jQuery.fn.applyClass = function(className,apply){
  if( apply ){
    $(this).addClass(className);
  } else {
    $(this).removeClass(className);
  }
  return this;
};

This is better than using toggleClass in cases where you might not know the state before toggling.

an example, say you want to show a navbar when you scroll 200px down

$(window).on('scroll',function(e){
    var top = $(window).scrollTop;
    $('.navbar').applyClass('show', ( top >= 200 ));
});

Comments

1

In newer JQuery, the best option is toggleClass, without jquery ui


$element
  .toggleClass('newClass', addClass)
  .toggleClass('myClass', foo && bar)
  .toggleClass('callback', () => true)

Comments

0

Either of the methods you have suggested will work.

This is an alternate method that allows you to chain multiple functions based on a conditional value:

var addClass=1; //or 0
var row=$('#cloneElement')
    .clone(false)
    .removeClass('gone')
    .removeAttr('id')
    .attr('data-id',this.id)
    .filter( function(){ return addClass === 1; })
    .addClass('newClass')
    .end();

2 Comments

Interesting. I've never used filter() or end(), but probably should start doing so
@user1032531 - Please don't. Code that uses filter and end is much harder to mentally parse. Focus on code readability, not the fewest keystrokes to solve something.

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.