Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do i change the color one by one to the items there with each click so that the previous one turns green again?

 <button>Click!</button>
        <ul>
            <li class="green">Home</li>
            <li class="green">faq</li>
            <li class="green">dropdown</li>
            <li class="green">about</li>
            <li class="green">contact</li>
        </ul>
let li = document.querySelectorAll('li');

let btn = document.querySelector('button');

for(let i=0; i<li.length; i++) {
    let number = 0;
    btn.addEventListener('click', ()=>{
        
    li[number++].classList.add('red')
       
        
        
        
        if(number === li.length) {
            number = 0
        }
    })
}

I wanted a single item to turn red with each click and the previous one to turn green again

I wanted a single item to turn red with each click and the previous one to turn green again

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it like this if this helps you. As soon as you press the button. Remove the red class from every element first and then add it like you were doing

let li = document.querySelectorAll('li');

let btn = document.querySelector('button');

for(let i=0; i<li.length; i++) {
    let number = 0;
    btn.addEventListener('click', ()=>{
      for(let i=0; i<li.length; i++) {
        li[i].classList.remove('red')
      }
      li[number++].classList.add('red')
      if(number === li.length) {
         number = 0
      }
    })
}
.green {
   color:green;
}

.red {
   color:red;
}
<button>Click!</button>
        <ul>
            <li class="green">Home</li>
            <li class="green">faq</li>
            <li class="green">dropdown</li>
            <li class="green">about</li>
            <li class="green">contact</li>
        </ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading