javascriptarraysgetelementsbyclassname

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.


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>