How can assign multiple css classes to an html element through javascript without using any libraries?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
just use this
take care about Space to avoid mix old class with new class
Try this:
Similar logic could be used to make a removeClass function.
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: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.
guaranteed to work on new browsers. the old className way may not, since it's deprecated.
Maybe this will help you learn:
This works: