Reputation: 1695
$("#" + parentElementId + " label").attr("class", "disabled")
VS
$('#radiolabel').addClass('disabled');
Which are the pros and cons?
Thanks
Upvotes: 2
Views: 131
Reputation: 707278
Here are some advantages of the two ways to do this:
addClass("disabled")
Pros:
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 common selector reasons so addClass()
makes it possible to add the disabled
class without disturbing other classes on the same object for other reasons.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:
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).Upvotes: 3
Reputation: 309
You better go for the addClass()
you will save time and writting, and gain more efficiency.
Upvotes: 1
Reputation: 78650
The 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.
Upvotes: 13
Reputation: 18682
I'd go for addClass
, it's easier to read, and if your editor supports code completion, also faster to type.
Upvotes: 3