0

I have found that editing an element seems to block onclick handlers, can someone explain this to me? I have done a recreation of the issue below:

The following code will result in two working buttons, which print the required messages to console:

<div id='testDiv'>

</div>

<script type="text/javascript">
    testDiv = document.querySelector('#testDiv')
    testDiv.innerHTML += `<button class="btn btn-primary test1" type="button">Test1</button>`
    testDiv.innerHTML += `<button class="btn btn-primary test2" type="button">Test2</button>`
    document.querySelector('.test1').onclick = function () {
        console.log('Test1')
    }
    document.querySelector('.test2').onclick = function () {
        console.log('Test2')
    }
</script>

The one below, where the innerhtml addition has been reordered now breaks the first button, so that only the second one results in the console message.

<div id='testDiv'>

</div>

<script type="text/javascript">
    testDiv = document.querySelector('#testDiv')
    testDiv.innerHTML += `<button class="btn btn-primary test1" type="button">Test1</button>`
    document.querySelector('.test1').onclick = function () {
        console.log('Test1')
    }
    testDiv.innerHTML += `<button class="btn btn-primary test2" type="button">Test2</button>`
    document.querySelector('.test2').onclick = function () {
        console.log('Test2')
    }
</script>
AAM
  • 35
  • 4

0 Answers0