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':'');
addClassmethod 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..addClass(..., condition)methods ... because a lot of times we do have conditions inside the chain code. API devs take note.