Home  >  Q&A  >  body text

javascript - Can I use setAttribute/removeAttribute to add or delete class names?

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梦2683 days ago961

reply all(3)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:48:49

    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,''); //删除类名

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:48:49

    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.

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:48:49

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

    reply
    0
  • Cancelreply