Benefits of using attr() over addClass in jquery

When you use attr method to set the class of any element it will override the existing class name with whatever value you pass as the second argument to attr method.

Where as if you use addClass method to add any class to an element it will just add the class and also retain the existing classes. If the class to add already exists then it will just ignore it.

E.g.

<div id="div1" class="oldClass"></div>

Using $('#div1').attr('class', 'newClass') will give

<div id="div1" class="newClass"></div>

Where as using $('#div1').addClass('newClass') will give

<div id="div1" class="oldClass newClass"></div>

So it is always adviseable to use addClass/removeClass to manupulate classes of html elements using jQuery. But at the end it depends on your requirement what to use when.

Leave a Comment