javascript - Can I use setAttribute/removeAttribute to add or delete class names?
过去多啦不再A梦
过去多啦不再A梦 2017-05-19 10:46:49
0
3
994

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? ?

过去多啦不再A梦
过去多啦不再A梦

reply all(3)
我想大声告诉你

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

ele.className += ' clsName'; //添加类名
ele.className = ele.className.replace(/ ?deleteClsName/g,''); //删除类名
曾经蜡笔没有小新

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. . . .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!