As the title says I’m supposed to change the text color of uneven li elements in my ul id="lista1". I can’t really figure out why this doesn’t work, looked on another site and someone had asked the same question and what I have in my code was the solution.
//HTML Code
<section id="DOM">
<header>
<h2>DOM</h2>
</header>
<article class="DOM-flex">
<h3>Lista 1</h3>
<ul id="lista1">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
</article>
<article class="DOM-flex">
<h3>Lista 2</h3>
<ul id="lista2">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
</article>
</section>
//Javascript Code
var list = document.getElementById('lista1');
for (var i = 0; i < list.length; i++){
if (i % 2 == 1) {
list.style.color = 'red';
}
}
>Solution :
//Javascript Code
var list = document.querySelectorAll('#lista1 li');
for (var i = 0; i < list.length; i++){
if (i % 2 !== 1) {
list[i].style.color = 'red';
}
}
<section id="DOM">
<header>
<h2>DOM</h2>
</header>
<article class="DOM-flex">
<h3>Lista 1</h3>
<ul id="lista1">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
</article>
<article class="DOM-flex">
<h3>Lista 2</h3>
<ul id="lista2">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
</article>
</section>
instead of referencing the list….I use querySelectorAll to get a collection of all the li elements…then loop through ….I also added the indexer [i] on the list variable inside the loop…I also changed the condition to !== since the array index is zero based….meaning item 1 in the list is at index 0 in the array….so to show ‘uneven list items’ in red….you actually need to highlight the even indices in the array