HTML:
<body>
<p>Colors</p>
<ul>
<li>Red</li>
<li>Green</li>
<li>Bleu</li>
</ul>
</body>
CSS:
body {
background-color: #8fbc8f;
font-family: Arial, sans-serif;
font-size: 1em;
}
.first { color: red; }
.second { color: green; }
.third { color: blue; }
我需要使用.setAttribute(),以便“红色”从CSS获得.first,“绿色”获得.second,“蓝色”获得.third。我已经尝试了很多东西,但是我不知道必须使用哪个名称和值,所以我的代码是正确的。
下面是我目前无法运行的脚本。有人可以告诉我该怎么做吗?
function Colors() {
let color = document.getElementsByTagName("li");
color[0].setAttribute("demo.css","first");
color[1].setAttribute("demo.css","second");
color[2].setAttribute("demo.css","third")
}
最佳答案
您要设置class
属性:
color[0].setAttribute("class", "first")
function Colors() {
let color = document.getElementsByTagName("li");
color[0].setAttribute("class", "first");
color[1].setAttribute("class", "second");
color[2].setAttribute("class", "third");
}
Colors()
body {
background-color: #8fbc8f;
font-family: Arial, sans-serif;
font-size: 1em;
}
.first { color: red; }
.second { color: green; }
.third { color: blue; }
<body>
<p>Colors</p>
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>
</body>