问题
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