Ajax3.14
Ajax3.14

Reputation: 1695

Which is better practice for adding a class using jQuery?

$("#" + parentElementId + " label").attr("class", "disabled")

VS

$('#radiolabel').addClass('disabled');

Which are the pros and cons?

Thanks

Upvotes: 2

Views: 131

Answers (4)

jfriend00
jfriend00

Reputation: 707278

Here are some advantages of the two ways to do this:

addClass("disabled") Pros:

  1. 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 common selector reasons so addClass() makes it possible to add the disabled class without disturbing other classes on the same object for other reasons.
  2. The code reads a little more self-explanatory since the name addClass() tells someone reading the code exactly what it's doing.
  3. 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:

  1. If you only ever want one class name on the object, this one statement insures that you will have only one class name.
  2. 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).

Upvotes: 3

Hristo Petev
Hristo Petev

Reputation: 309

You better go for the addClass() you will save time and writting, and gain more efficiency.

Upvotes: 1

James Montagne
James Montagne

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

fivedigit
fivedigit

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

Related Questions