skip to Main Content

I have 2 buttons that are dynamically injected on a page, both buttons have a click event listener attached to them.

When a div gets injected with Button A but not Button B, Button A works. However, when Button A as well as Button B get injected side-by-side, only Button B works.

Button A

HTML

<div id="1" class="classA" style="margin-left: 8px; margin-bottom: 14px;">
  <i class="fa fa fa-plus-circle"></i>
</div>

JS

document.getElementById('1').addEventListener('click', async () => {
  functionA()
})

Button B

HTML

<div id="2" class="classB" style="margin-left: 8px; margin-bottom: 14px;">
  <i class="fa fa fa-clock-o"></i>
</div>

JS

document.getElementById('2').addEventListener('click', async () => {
  functionB()
})

The way I’m injecting is by looping over elements on the page then using document.getElementsByClassName('ClassName')[i].innerHTML += Button to add the button, Button A is always added first, Button B gets removed after it’s clicked but even then Button A’s event doesn’t fire. Both buttons are added the exact same way, just different loops.

2

Answers


  1. Unfortunately I am unable to comment and must post an answer (not enough reputation to do comments).

    Could you confirm if after the injection, you can see both button elements? It is not possible to tell from the available code. There could be something overlapping Button A and preventing you from interacting with it.

    How about console errors? Open up devtools to see if there’s anything there.

    Inject both buttons, and try to run document.getElementById("1").onclick() in the devtools console. What do you get?

    Login or Signup to reply.
  2. First of all, div elements are not made to be used as buttons. There is button element for it. In addition it’ll have better compatibility with screen readers.

    <button id="1" class="classA" style="margin-left: 8px; margin-bottom: 14px;">
      <i class="fa fa-plus-circle"></i>
    </button>
    

    I’m not sure how your full code looks, but if it actually just calls an another function, there’s a way to simplify it:

    document.getElementById('1').addEventListener('click', functionA)
    

    If you are not sure if it works, open console and call this line of code:

    document.getElementById('1').click()
    

    This will fire all events tied to the click event.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search