Home > Mobile >  How can I ignore white space when using classList.add?
How can I ignore white space when using classList.add?

Time:12-10

I'm trying to add classes to an element in JS using classList.add(), if I have input like this ("one two") separated by whitespace how can I take each part as a class ?

let element = document.querySelector(".element")
element.classList.add("one two")

CodePudding user response:

Add multiple classes into an element:

element.classList.add("one", "two"); 

or

element.classList.add("two"); 
element.classList.add("one"); 

To use classes from an input, seperated by space:

const userInput = "one two";
element.classList.add(...userInput.split(" "));

CodePudding user response:

const str = 'one two three';
const classes = str.split(' ');
document.querySelector(".element").classList.add(...classes);
  • Related