Home > Back-end >  How to select with dom a random child element from an element in Javascript?
How to select with dom a random child element from an element in Javascript?

Time:11-07

i started an interactive rating card.

The goal is to choose a number how you would rate and then to submit your answer.

i want to chose a number and then with and eventlistner to change the background of the div element of the choosen number from the current background to another color. So far i have the submit button and recive a thank you message on the card after the button.

this is the html of the 5 number you can choose to rate

 <div >
          <div >1</div>
          <div >2</div>
          <div >3</div>
          <div >4</div>
          <div >5</div>
        </div>

this is the css for example for the first div. All divs have the same css code

.one {
  width: 60px;
  height: 60px;
  color: var(--text-color);
  background-color: var(--background-color-body);

  border-radius: 50%;
  justify-content: center;
  align-items: center;
  display: flex;
  font-weight: 800;
}

I tried with a for Loop to go through all the numbers and by clicking to change the backgroug color

this was the javascript code i tried

addEventListener('click', myFunction);
{
  function myFunction() {
    var drugi = document.querySelectorAll('.numbers div');
    for (i = 0; i <= element.length; i  ) {
      element[i].style.backgroundColor = 'white';
    }
  }
}

CodePudding user response:

There are three problems wit your .js code. First, you have the function myFunction in a different scope than the event listener addEventListener('click', myFunction). So to fix it just remove the keys that wrap it. Second, you are using the element before declaring it. And third, the loop will assign the same color to all the element. (Notice a background color white will be not noticed).

To fix it, just use the event delegation pattern on the parent (which is the div element with the class numbers) and check if the target is a div element with the class number and then change the background color.

const numbers = document.querySelector('.numbers')
numbers.addEventListener('click', () => {
  const target = event.target
  if (target.className === 'numbers') return
  target.style.backgroundColor = 'blue'
})
  • Related