简体   繁体   English

使用 .classList.add 方法时出现 DOM 错误

[英]DOM error while using .classList.add method

So when I'm trying to add two classes to my elemeny by this code所以当我试图通过这段代码向我的元素添加两个类时

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我在这里没有看到任何不正确的空白

What seems to be the issue is that curr_class is a string containing a space问题似乎是curr_class是一个包含空格的字符串

According to the doc https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList根据文档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另请注意,您的代码所做的是:它采用元素的类并将其添加到同一元素中,因此没有任何用处

It seems like you have a space in your class name: 1 cell-red between 1 and cell-red .您的类名中似乎有一个空格: 1 cell-red之间的1 cell-red

One solution would be to add the classes one by one:一种解决方案是一一添加类:

myElement.classList.add('1');
myElement.classList.add('cell-red');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM