javascript – className, SetAttribute ou classList.add

Question:

I have a JSON list that creates various blog objects and I came across the following ways to add classes to the HTML objects I create after loading the list: className, setAttribute and classList.add.

Obviously I'm giving preference to classList.add or even className, but I found that setAttribute performs comparable or even better than them. How would this CSS class definition look inside the private set, does anyone have any recommendations?

Answer:

The setAttribute should never be used to add a class to an element, for the simple fact that the new value will override the current one and you have no control over which classes the element currently has. If in one part you add the x class and in the other the y class, you will have a lot of inconsistency in your layout. To get around this problem, you would have to read the current value and concatenate the new class to it, but that's exactly what className does.

Now, between choosing className and classList , the MDN documentation itself, for example, answers this:

Using classList is a convenient alternative to accessing an element's class list as a space-delimited string through element.className .

The only thing is that classList may not be implemented in all browsers you intend to support, so check the compatibility table before using it in production.

Scroll to Top