Search code examples
javascripthtmljquerycssinnerhtml

Weird bug when "innerHTML" is used..?


I found a weird error that I could not understand. Can someone please explain why below code is not working? Button2 stops working when I put it inside of the <div id='test'>.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<button id='button1'>Button1</button>


<div id='test'>
    <button id='button2'>Button2</button>
</div>

<script>
//Global var
var content = document.getElementById('test');

$(document).ready(function(){
    $('#button1').on('click', function(){
        content.innerHTML += '<hr>';
    });
});

$(document).ready(function(){
    $('#button2').on('click', function(){
        content.innerHTML += ' Test';
    });
});

</script>
</body>
</html>

Solution

  • "event" is no longer valid when you change the element. Feed from the upper element to remain in the "event".

     $('#button2').on('click', function(){
    
     replace width:
    
     $('body').on('click', '#button2', function () {