JavaScript element.classList.add(“fa fa-hand-rock-o”) Error: “String contains an invalid character”

為{幸葍}努か 提交于 2021-01-27 05:43:40

问题


I'm trying to add a class to <span id="sp1"> using:

document.getElementById("sp1").classList.add("fa fa-hand-rock-o");

But it is showing error:

String contains an invalid character


回答1:


fa fa-hand-rock-o can not be a single class because class names can not have space(s).

Here I assume you are trying to add two different classes. When adding multiple classes by using classList.add() specify all the classes as individual comma separated string like:

.add("fa", "fa-hand-rock-o")

Code Example:

document.getElementById("sp1").classList.add("fa","fa-hand-rock-o");

console.log(document.getElementById("sp1"));
<span id="sp1">Test Container</span >



回答2:


The white space between two class name is creating the issue.If need to add multiple class separate them by a comma and put each of them inside a quote

document.getElementById("sp1").classList.add("fa", "fa-hand-rock-o")
.fa {
  color: red;
}

.fa-hand-rock-o {
  font-size: 18px;
}
<li id="sp1"> Test Text </li>


来源:https://stackoverflow.com/questions/49348858/javascript-element-classlist-addfa-fa-hand-rock-o-error-string-contains-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!