js: <input> field seems to be in memory twice after removing and re-adding to the DOM


I have an <input> element in html, inside a button:


<button class="green button " id="playPause"> &nbsp;Play in&nbsp;&nbsp; <input type="text" 
 id="timeInputInButton" maxlength="3" size="2" value="3" 
 style="text-align:right; padding-bottom:1px; padding-top:1px; padding-right:2px; margin-bottom:0px; margin-top:0px;" > 
 sec </button> 

and in JS:

const timeInput = document.getElementById('timeInputInButton');

Now everythings works as expected: When I now say timeInput.value = 100 the displayed value jumps to 100.

But as soon as I remove the timeInputfrom the DOM and then (later) add it back again, it bahaves as if I had 2 <input>elements with the same ìd.

That’s how I remove the element (even though it’s the same if I use .removeChild()):

const playPauseButton = document.getElementById('playPause');
playPauseButton.innerHTML = "Pause";

And how I re-add it (doesn’t matter if I use appendChildor append):


Now if I say timeInput.value = 100 the GUI doesn’t update.

timeInput.value = 100, but

document.getElementById('timeInputInButton').value returns the default value the input field had at the time of the variable binding const timeInput = document.getElementById('timeInputInButton');

Why does it look like I have 2 <input> elements in memory?


This is undoubtedly related to the fact that interactive content is not allowed within a <button> element. Although the browser allows this and does what it can to make the flawed encapsulation work, using HTML inappropriately has consequences.

MDN Reference

Answered By – Randy Casburn

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.