JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<body>
B1 has it's script-handler outside of its div. Replacing B1 would leave the code alive, but it'd never fire again because there's no element left to trigger the event
<div id="foo">
<button>
B1 - I replace B2
</button>
</div>
<script>
jQuery("#foo button").click(function() {
console.log("B1-clicked");
jQuery("#bar").html(jQuery("<button>B2</button>"));
});
</script>
B2 has it's own private script-tag with an event handler (inside the #bar div). Clicking B1 will not only replace B2, it'll also remove the script-tag, which leaves a button without an event handler. Pressing B2 after B1 has been pressed, does nothing.
<div id="bar">
<button>
B2
</button>
<script>
jQuery("#bar button").click(function() {
console.log("B2-clicked");
});
</script>
</div>
B3 will also replace B2 but it'll also add another event-handler to B2. Clicking B2 after B3 has been pressed will write to the console.
<div id="baz">
<button>
B3 - I replace B2 and it's click handler
</button>
<script>
jQuery("#baz button").click(function() {
console.log("B3-clicked");
jQuery("#bar").html(jQuery("<button>B2</button>"));
jQuery("#bar button").click(function() {
console.log("B2-clicked, again");
});
});
</script>
</div>
</body>
</html>
CSS
div {
margin: 4px;
padding: 10px;
}
#foo {
background-color: #fab;
}
#bar {
background-color: #afb;
}
#baz {
background-color: #baf;
}