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 to select with dom a random child element from an element in Javascript?

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.

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

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

 <div class="numbers">
          <div class="one">1</div>
          <div class="two">2</div>
          <div class="three">3</div>
          <div class="four">4</div>
          <div class="five">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';
    }
  }
}

>Solution :

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'
})
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