JavaScript CSS how to add and remove multiple CSS classes to an element

前端 未结 14 1894
迷失自我
迷失自我 2020-12-07 21:46

How can assign multiple css classes to an html element through javascript without using any libraries?

相关标签:
14条回答
  • 2020-12-07 22:45

    Try this:

    function addClass(element, value) {
      if(!element.className) {
        element.className = value;
      } else {
        newClassName = element.className;
        newClassName+= " ";
        newClassName+= value;
        element.className = newClassName;
      }
    }
    

    Similar logic could be used to make a removeClass function.

    0 讨论(0)
  • 2020-12-07 22:45
      addClass(element, className1, className2){
        element.classList.add(className1, className2);
      }
      removeClass(element, className1, className2) {
        element.classList.remove(className1, className2);
      }
    
    removeClass(myElement, 'myClass1', 'myClass2');
    addClass(myElement, 'myClass1', 'myClass2');
    
    0 讨论(0)
提交回复
热议问题