How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  眼角桃花
    2020-11-21 11:56

    I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.

    Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.

    'use strict'
    
    const oldAdd = (element, className) => {
      let classes = element.className.split(' ')
      if (classes.indexOf(className) < 0) {
        classes.push(className)
      }
      element.className = classes.join(' ')
    }
    
    const oldRemove = (element, className) => {
      let classes = element.className.split(' ')
      const idx = classes.indexOf(className)
      if (idx > -1) {
        classes.splice(idx, 1)
      }
      element.className = classes.join(' ')
    }
    
    const addClass = (element, className) => {
      if (element.classList) {
        element.classList.add(className)
      } else {
        oldAdd(element, className)
      }
    }
    
    const removeClass = (element, className) => {
      if (element.classList) {
        element.classList.remove(className)
      } else {
        oldRemove(element, className)
      }
    }

提交回复
热议问题