0

I'm currently learning web development with CSS, HTML and JavaScript.

This is my code:

const items = document.querySelectorAll('#players li');
console.log(items[0], items[1], items[2]);
<section id="players">
  <h1>Test</h1>
  <ol>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
  </ol>
</section>

What I want to do is to make a specific list item, let's say the third one to have a specific color. I can't figure out to how to use the style property to set the CSS-property color externally in my JavaScript file.

3
  • Hi and welcome to Stack Overflow! Did you know you can achieve your question with CSS only? Is that okay? Commented May 27, 2020 at 9:55
  • Something like items[2].style.color = 'red'; to have your third element in red color. See the documentation Commented May 27, 2020 at 9:57
  • Yes that is okay. Commented May 27, 2020 at 10:02

2 Answers 2

1

You could apply color through the JavaScript style property, e.g.:

const items = document.querySelectorAll('#players li');
if (items.length > 2) {
  items[2].style.color = "red";
}
<section id="players">
  <h1>Test</h1>
  <ol>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
  </ol>
</section>

Or you can achieve the same result just with the CSS nth-child selector:

#players li:nth-child(3) {
  color: red;
}
<section id="players">
  <h1>Test</h1>
  <ol>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
  </ol>
</section>

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

Comments

1

Iterate items using forEach and check the index. Since the collection starts with 0 for third one you need to check if current index is 2 then use classList.add to add a class and style it

const items = document.querySelectorAll('#players li');
items.forEach((item, index) => {
  if (index === 2) {
    item.classList.add('custom')
  }
})
.custom {
  background: yellow;
}
<section id="players">
  <h1>Test</h1>
  <ol>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
  </ol>
</section>

2 Comments

Doing a forEach has a O(n)-complexity. Since the index is known in advance, you could simply work with items[2] (O(1)).
How do I use this for-loop to iterate through list-item to use the style-property on these elements to set text-decoration to underline?

Your Answer

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