getElementById('hidden-div').innerHTML
returns a string
, not DOM elements. That string is passed to #div2
and parsed into new DOM elements, meaning the initially bound event is no longer bound on the <input>
.
In fact, innerHTML
is the common method to copy HTML without any bound events.
To keep the event you have two options:
- bind it to
#div2
instead of the button
- or don't destroy the
<input>
. Instead, append it using appendChild
.
Binding to #div2
:
document.getElementById('btn1').addEventListener("click", function() {
document.getElementById('div2').innerHTML = document.getElementById('hidden-div').innerHTML;
});
document.getElementById('div2').addEventListener("click", function() {
document.getElementById('div-main').innerHTML = "";
});
<div id="div-main">
<input type="button" name="button1" value="button1" id="btn1">
</div>
<div id="div2">
</div>
<div style="display: none;">
<div id="hidden-div">
<input type="button" name="button2" value="button2" id="btn2">
</div>
</div>
Using appendChild
:
document.getElementById('btn1').addEventListener("click", function() {
let children = document.getElementById('hidden-div').children;
for (let i = 0; i < children.length; i++) {
document.getElementById('div2').appendChild(children[i]);
}
});
document.getElementById('btn2').addEventListener("click", function() {
document.getElementById('div-main').innerHTML = "";
});
<div id="div-main">
<input type="button" name="button1" value="button1" id="btn1">
</div>
<div id="div2">
</div>
<div style="display: none;">
<div id="hidden-div">
<input type="button" name="button2" value="button2" id="btn2">
</div>
</div>
Important note: moving the binding inside the click
function means the binding will be done each time #btn1
is clicked. It's not a problem in your case, as you're destroying and recreating the contents of #div2
as well, but if you use the same logic to another construct, which doesn't wipe the contents, you'll bind the same function multiple times, which is dangerous as it may lead to hard to detect bugs.