0

How to call same onclick function on multiple element? I want to make show text and show div onclick function as a single click.

I want to call a onclick function that opens div and changes backgoundcolor and fontcolor when I click on any of parts.

Now onclick function only works on first element. Please help.

function myFunction() {
  document.getElementById("answer").style.color = "red";
  document.getElementById("answer").style.backgroundColor = "white";
  var x = document.getElementById("explain");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<div class="test">
<ul class="example">
<li>This is</li>
<li id="answer" onclick="myFunction()" style="background-color:#444444; color:#444444;">example.
</li>
</ul>
<ul id="explain" style="display:none">
TEST1
</ul>
</div>
<div class="test">
<ul class="example">
<li>This is</li>
<li id="answer" onclick="myFunction()" style="background-color:#444444; color:#444444;">example2.
</li>
</ul>
<ul id="explain" style="display:none">
TEST2
</ul>
</div>
<div class="test">...</div> X Loop
JIEUN KIM
  • 1
  • 1
  • 1
    did u tried instead of a "," comma a ";" ? – Leonardocregis Jul 07 '20 at 14:37
  • Does this answer your question? [How to call multiple JavaScript functions in onclick event?](https://stackoverflow.com/questions/3910736/how-to-call-multiple-javascript-functions-in-onclick-event) – harish kumar Jul 07 '20 at 14:39
  • I can't figure out what the author is asking. – Rick Jul 07 '20 at 14:53
  • Sorry myFunction2() is my mistake. Now i deleted. I mean
    is Loop. But now function only works on first div.
    – JIEUN KIM Jul 07 '20 at 21:53