Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM error while using .classList.add method

Tags:

javascript

So when I'm trying to add two classes to my elemeny by this code

var curr_class = document.getElementById(hover_start).className
document.getElementById(hover_start).classList.add("cell-red",curr_class)

I have this error

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

I don't see any incorrect white space in here

like image 864
pol Avatar asked May 16 '26 09:05

pol


2 Answers

What seems to be the issue is that curr_class is a string containing a space

According to the doc https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList

You should add the class one by one.

Note also that what your code does is : it takes the class of an element and adds it to the same element so nothing usefull

like image 106
CharybdeBE Avatar answered May 17 '26 21:05

CharybdeBE


It seems like you have a space in your class name: 1 cell-red between 1 and cell-red.

One solution would be to add the classes one by one:

myElement.classList.add('1');
myElement.classList.add('cell-red');
like image 24
Lucian Tarbă Avatar answered May 17 '26 23:05

Lucian Tarbă



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!