enter image description here
Hello, there are three buttons, click on it, a circle is painted in some color, how can this be done?

I am quite a novice, I started doing it as follows, but then I got up in a stupor. On when you need to refer to this to color the button on which the event occurred.

But one moment, you need to paint not the button itself, but an absolutely positioned element inside it, i.e. circle;

Here is the code:

 var btn = document.querySelectorAll('.button'); var change = document.getElementsByClassName('change-element'); function test(){ for (var index = 0; index<change.length; index++) { change[index].style.backgroundColor="black"; } } for (var i = 0; i<btn.length; i++) { btn[i].addEventListener("click", test); } 
  • 2
    Add to style solid - nick_n_a
  • why not use jQuery for this? - Diefair
  • one
    @Diefair, because the javascript label is Grundy

2 answers 2

Maybe so:

 var btn = document.querySelectorAll('.button'); function test() { this.getElementsByClassName('change-element')[0].style.backgroundColor = "black"; } for (var i = 0; i < btn.length; i++) { btn[i].addEventListener("click", test); } 
 ul>li { list-style: none; } .change-element { width: 50px; height: 50px; background-color: red; } 
 <div> <ul> <li class="button">Button1 <span class="change-element">111</span> </li> <li class="button">Button2 <span class="change-element">111</span> </li> </ul> </div> 

  • But both of them are painted, and only that one should click on) - GoodNew5
  • @ Alexander Veselov like radio? - C.Raf.T

Resolved:

 var btn = document.querySelectorAll('.button'); var change = document.getElementsByClassName('change-element'); function test(){ for (var index = 0; index<change.length; index++) { change[index].style.backgroundColor="#95a5a6"; } this.getElementsByClassName('change-element')[0].style.backgroundColor="red"; } for (var i = 0; i<btn.length; i++) { btn[i].addEventListener("click", test); } 
  • one
    Isn't it better to hang the event on a container and then check the event.target? Yes, and use pseudo-elements for buttons. - pepel_xD