0

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; }

I need to use the .setAttribute() so that 'Red' gets the .first from CSS, 'Green' gets the .second and 'Blue' gets the .third. I've tried many things but i don't know which name and value I have to use so my code is correct.

Below is my script at the moment which doesn't seem to work. Can somebody tell me how I can do this?

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 Answer 1

1

You want to set the class attribute:

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>

Sign up to request clarification or add additional context in comments.

1 Comment

probably better at this point to use the element.classList interface to reconcile dynamic class names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.