0

For adding a class we can use like the below

$('#x').addClass('test');

we can also do by the following way

$('#x').attr('class','test');

So I want to know are these both the ways same and there are some differences

SpringLearner
  • 13,738
  • 20
  • 78
  • 116

2 Answers2

2

$('#x').attr('class','test'); will remove all existing class and set test as the only class...

where as $('#x').addClass('test'); will add the class test to existing set of classes if it is already not present

<div id="x" class="some class"></div>

In the above markup .addClass('test') will result in class="some class test", where as .attr('class','test') will create class="test"

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Example :

<div id="x" class="a">

$('#x').addClass('test');

Result:

<div id="x" class="a test">

$('#x').attr('class','test');

Result:

<div id="x" class="test">

But if you talking about perf. See this..

http://jsperf.com/jquery-addclass-vs-attr-class-vs-prop-class/3

l2aelba
  • 21,591
  • 22
  • 102
  • 138