How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  野的像风
    2020-11-21 12:08

    For those using Lodash and wanting to update className string:

    // get element reference
    var elem = document.getElementById('myElement');
    
    // add some classes. Eg. 'nav' and 'nav header'
    elem.className = _.chain(elem.className).split(/[\s]+/).union(['nav','navHeader']).join(' ').value()
    
    // remove the added classes
    elem.className = _.chain(elem.className).split(/[\s]+/).difference(['nav','navHeader']).join(' ').value()
    

提交回复
热议问题