In the group discussion about the operation of class names in native js, someone suggested that the setAttribute and removeAttribute methods can be used to operate the class names. I felt very puzzled: I thought there were only classList.add() or classList.remove( ) This method can solve this need, but someone has proposed using setAttribute('class', 'xxx') and removeAttribute('class'). The first feeling is that it is limited and unsafe: first, the class name can only be changed to the specified result, and second, the method of deleting the class attribute has never been seen before. I would like to ask if this approach is feasible in the operation of class names? ?
In fact, if you just want to handle adding and deleting classes, you can also choose to use className, which can also avoid compatibility issues with classList.
You can choose to encapsulate the two addition and deletion methods yourself.
The implementation code is as follows
The browser version of
removeAttribute
是用来删除指定属性的,class
也是属性,自然可以删除。classList
是 HTML5 的 API,如果只能用它来添加删除,你让不支持classList
is so embarrassing. In addition, you will know if you try this kind of problem.Why not addClass....
setAttribute modifies the overall attribute of class. If you want to use it to deal with class, you still need to make a judgment
class="test1 test2 test3"; In this case, if you want to setAttribute, you need to first determine whether your value exists. If it does not exist, it will be added. If it exists, it will not be processed. For remove, you have to determine whether it exists. If it does not exist, it will not be processed. If it exists, you cannot delete the others. . . .