$("#" + parentElementId + " label").attr("class", "disabled")
VS
$('#radiolabel').addClass('disabled');
Which are the pros and cons?
Thanks
$("#" + parentElementId + " label").attr("class", "disabled")
VS
$('#radiolabel').addClass('disabled');
Which are the pros and cons?
Thanks
Share Improve this question edited Feb 1, 2012 at 21:37 weltraumpirat 22.6k5 gold badges43 silver badges54 bronze badges asked Feb 1, 2012 at 21:29 Ajax3.14Ajax3.14 1,6955 gold badges24 silver badges42 bronze badges4 Answers
Reset to default 13The two are not the same. Using attr
will replace the whole attribute. addClass
will add the class to the existing classes.
As the name suggests addClass
is made for this specific purpose, so I'd use that.
Here are some advantages of the two ways to do this:
addClass("disabled")
Pros:
- If you have other classes on your object,
addClass()
will preserve those while adding a new class. I pretty much always want to preserve the ability to use other classes for CSS styling reasons or mon selector reasons soaddClass()
makes it possible to add thedisabled
class without disturbing other classes on the same object for other reasons. - The code reads a little more self-explanatory since the name
addClass()
tells someone reading the code exactly what it's doing. addClass()
automatically manages separators between class names so there is no extra accumulation of separators when you have multiple class names which can occur if you just get the current classname and add onto it yourself with string manipulation.
attr("class") = "disabled"
Pros:
- If you only ever want one class name on the object, this one statement insures that you will have only one class name.
- A direct assignment of the one class can be faster than
addClass()
which has to examine what's there first and add a class to the pre-existing classes which jQuery does with a regex match. Max speed would actually be with element.className = "disabled" (no jQuery at all).
I'd go for addClass
, it's easier to read, and if your editor supports code pletion, also faster to type.
You better go for the addClass()
you will save time and writting, and gain more efficiency.