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

前端 未结 14 1958
迷失自我
迷失自我 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:29

    Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):

    div.classList.add('foo', 'bar'); // add multiple classes

    From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

    If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:

    let classesToAdd = [ 'foo', 'bar', 'baz' ];
    div.classList.add(...classesToAdd);
    

    Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.

提交回复
热议问题