After searching the MDN website, W3chools and running tests on my browser and measurethat, I discovered some interesting things about the 3 methods. As they vary in speed and functionality, I set up a post to explain how I got to my answer.. below is a summary of it
The performance
I decided to search to know what would be the best option. According to the site https://measurethat.net/Benchmarks/Show/54/0/classname-vs-setattribute-vs-classlist, someone had already wondered the same. They did the following test I ran on Chrome, Edge and Firefox:
1st place: class
2nd place: setAttribute (except Edge)
3rd place: classList
*Result in transactions per second
In practice
Even if it is very clear, the above test is not an absolute, we must take into account other factors such as manipulation, functionalities and good practices.
classname: Allows the manipulation of classes in string format, in this case having a string with all classes written inside and allowing the manipulation of the data in this format. As an old feature, it is used by several browsers
setAttribute: The set attribute simply does this, sets the value within an attribute. There is getattribute that lets you view this value, but manipulation is limited to this.
classList: Places classes within a list to be manipulated in an orderly manner through several specific methods. The level of functionality is the most practical, but besides having a lower performance, has not been implemented in older browsers.
Completion
I believe that classname and classList are the best candidates. If you need performance and are just setting and deleting classes, use the classname. Now if you have a system that needs to search for classes within the tag or add only if it doesn’t exist, save the effort of creating a logic for it and use the classList.
For the full version of this reply, see the post: http://www.mundojs.com.br/blog/b00020.html
Hi Anderson, I came to the same conclusion about the setattribute because it doesn’t really help, maybe in the case of being only 1 class and not moving anymore. of the rest I agree with you, I joined the MDN and performance test site and ended up choosing the classList for malleability. Thank you
– Paulo Künzel