0

I'm trying to add multiple css selectors to an element using classList that's inside a function, but keep getting the below error. How do I do this right?

Uncaught DOMException: Failed to execute 'add' on 'DOMTokenList': 
The token provided ('padding fonts') contains HTML space characters, which are not valid in tokens.

https://jsfiddle.net/nordy/h84gadst/1/

function addStyle(element,styleName) {
    element.classList.add(styleName);
}

var targetElement = document.getElementById("parent-container");

var addStyleElement = document.getElementById("addStyle");

addStyleElement.onclick = function() {
    addStyle(targetElement,'padding fonts');
}
1
  • 1
    The issue is that you're adding more than one class. It does not work that way. To add multiple classes we do like so div.classList.add("foo", "bar", "baz"); not div.classList.add("foo bar baz"); as you're doing. Commented Oct 14, 2020 at 6:19

2 Answers 2

2

The main problem is that classes cannot contain spaces, you can add multiple classes separated with comas like this:

element.classList.add('padding','fonts');

EDIT: If you want to send multiple classes in the same string, you can do this in the method:

function addStyle(element,styleName) {
    styleName.split(" ").forEach(class => element.classList.add(class));
}
Sign up to request clarification or add additional context in comments.

2 Comments

So how do I call addStyle() when using multiple selectors?
@Norman you can do a .split(" ") in the method, and then doing a classList.add() for each one
1

If you do it like this it should work, the space is the issue

addStyleElement.onclick = function() {
addStyle(targetElement,'padding');
addStyle(targetElement,'fonts');

}

4 Comments

I'm trying to do it together addStyle(targetElement,'padding fonts')
I understand but the space is generating the error
Edit your function definition like so: function addStyle(element,styles) { element.classList.add(...styles); } We take the help of the spread operator. Now you can call it like this: addStyleElement.onclick = function() { addStyle(targetElement,['padding', 'fonts']); } Hope this helps you.
Solves the problem, but won't work for IE users.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.