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
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
$('#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"
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