How do I add a class to a given element?

前端 未结 25 2364
清酒与你
清酒与你 2020-11-21 11:34

I have an element that already has a class:

25条回答
  •  清酒与你
    2020-11-21 12:06

    I know IE9 is shutdown officially and we can achieve it with element.classList as many told above but I just tried to learn how it works without classList with help of many answers above I could learn it.

    Below code extends many answers above and improves them by avoiding adding duplicate classes.

    function addClass(element,className){
      var classArray = className.split(' ');
      classArray.forEach(function (className) {
        if(!hasClass(element,className)){
          element.className += " "+className;
        }
      });            
    }
    //this will add 5 only once
    addClass(document.querySelector('#getbyid'),'3 4 5 5 5');
    

提交回复
热议问题