How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  感动是毒
    2020-11-21 12:14

    You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.

     //select the dom element
     var addClassVar = document.querySelector('.someclass');
    
     //define the addclass function
     var addClass = function(el,className){
       if (el.classList){
         el.classList.add(className);
       }
       else {
         el.className += ' ' + className;
      }
    };
    
    //call the function
    addClass(addClassVar, 'newClass');
    

提交回复
热议问题