JavaScript将css插入.setAttribute()

时间:2017-01-08 17:20:45

标签: javascript html css

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(),以便'Red'从CSS获取.first,'Green'获取.second,'Blue'获取.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")
}

1 个答案:

答案 0 :(得分:1)

您想要设置class属性:

color[0].setAttribute("class", "first")

&#13;
&#13;
function Colors() {
    let color = document.getElementsByTagName("li");
    color[0].setAttribute("class", "first");
    color[1].setAttribute("class", "second");
    color[2].setAttribute("class", "third");
}
Colors()
&#13;
body {
        background-color: #8fbc8f;
        font-family: Arial, sans-serif;
        font-size: 1em;
    }

.first { color: red; }
.second { color: green; }
.third { color: blue; }
&#13;
<body>
    <p>Colors</p>
    <ul>
        <li>Red</li>
        <li>Green</li>
        <li>Blue</li>
    </ul>
</body>
&#13;
&#13;
&#13;