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 can I handle multiple button?

I want to handle multiple buttons. My aim is when a user will click on the first button then the first paragraph will be changed, again when a user will click on the second button then the second paragraph will be changed. I tried, but not working. Please check my code and give me a solution….

var len = document.querySelectorAll(".myButton").length
var plen = document.querySelectorAll(".myP").length
for (i = 0; i < len; i++) {
  for (j = 0; j < plen; j++) {
    document.querySelectorAll(".myButton")[i].addEventListener("click", function() {
      if (document.querySelectorAll(".myButton")[i] == document.querySelectorAll(".myP")[j]) {
        document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;
      }
    });
  }
}
<p class="myP">oke</p>
<p class="myP">oke</p>

<h1 class="pt-3 pb-3 pl-5 pr-5 bg-warning text-light btn mx-5 my-5">00</h1><br>
<hr style="background-color:red; width:50%">
<button class="btn bg-primary text-light mx-5 my-5 myButton">one</button>
<button class="btn bg-primary text-light mx-5 my-5 myButton">two</button>

error:

5_eventListener.html:43 Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')
    at HTMLButtonElement.<anonymous> (5_eventListener.html:43:119)

Error line:

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

document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;

>Solution :

Your code needs closures to work and that is quite tricky

Instead delegate – here I delegate from document, but if the buttons have a wrapper, you can delegate from that

Much simpler. Also use data attributes to give a target to the buttons

document.addEventListener("click", function(e) {
  const tgt = e.target;
  if (!tgt.matches(".myButton")) return 
  document.getElementById(tgt.dataset.target).innerHTML = tgt.innerHTML;
})  
<p class="myP" id="p1">oke</p>
<p class="myP" id="p2">oke</p>

<h1 class="pt-3 pb-3 pl-5 pr-5 bg-warning text-light btn mx-5 my-5">00</h1><br>
<hr style="background-color:red; width:50%">

<button class="btn bg-primary text-light mx-5 my-5 myButton" data-target="p1">one</button>
<button class="btn bg-primary text-light mx-5 my-5 myButton" data-target="p2">two</button>
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