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
6
  • Where else are you trying to use myFunction and how is it failing? Where do you define myFunction2? Commented Jul 7, 2020 at 14:35
  • Do you mean you want to call both myFunction() and myFunction2() on click of your <li> Commented Jul 7, 2020 at 14:35
  • 1
    did u tried instead of a "," comma a ";" ? Commented Jul 7, 2020 at 14:37
  • Does this answer your question? How to call multiple JavaScript functions in onclick event? Commented Jul 7, 2020 at 14:39
  • I can't figure out what the author is asking. Commented Jul 7, 2020 at 14:53

1 Answer 1

1

Separate function names by semicolon.

onclick="myFunction();myFunction2()"

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.