Conditionally add class using jQuery
javascript, jquery
Solution
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.
Problem
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':''); ```