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 make only one class div element changeable, so that if one is clicked, others can't be? Javascript

I’m trying to make a rating system, so that only one div at a time can be changed, but all of them can still be clicked.

const number = document.getElementsByClassName('number');

function changeColor(arg) {
  arg.addEventListener('click', () => {
    arg.style.backgroundColor = 'hsl(216, 12%, 54%)';
    arg.style.color = 'white';
  })
}


for (let i = 0; i < number.length; i++) {
  changeColor(number[i]);
}
<div class="number icon"><h2>1</h2></div>
<div class="number icon"><h2>2</h2></div>
<div class="number icon"><h2>3</h2></div>
<div class="number icon"><h2>4</h2></div>
<div class="number icon"><h2>5</h2></div>

  

I figured out how to make class elements changeable on click with a loop, but now they can all be changed which isn’t what I want. I found some similar answers but they are in jQuery which I unfortunately don’t know yet.

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 :

Assuming you want to reset the other number when a new number is selected. Added a resetAll() function before the new number is highlighted.

const number = document.getElementsByClassName('number');

function changeColor(arg) { 
     arg.addEventListener('click', () => {
     
        resetAll();
     
        arg.style.backgroundColor = 'hsl(216, 12%, 54%)';
        arg.style.color = 'white';
     })
}

function resetAll () {
  for(let i = 0; i < number.length; i++) {
        number[i].style.backgroundColor = 'unset';
        number[i].style.color = 'unset';
  }
}


for(let i = 0; i < number.length; i++) {
    changeColor(number[i]);
} 
<div class="number icon"><h2>1</h2></div>
<div class="number icon"><h2>2</h2></div>
<div class="number icon"><h2>3</h2></div>
<div class="number icon"><h2>4</h2></div>
<div class="number icon"><h2>5</h2></div>
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