javascript innerHTML adding instead of replacing
Notice that using element.innerHTML += 'content'
would empty input
s and textarea
s to their default, blank state, unclick checkboxes, as well as removing any events attached to those elements (such as onclick
, on hover
etc.) because the whole innerHTML
would be reinterpreted by the browser, which means .innerHTML
is emptied and filled again from scratch with the combined content.
If you need to keep the state, you'd need to create a new element (a <span>
for instance) and append it to the current element, as in:
let newElement = 'span'
newElement.innerHTML = 'new text'
document.getElementById('oldElement').appendChild(newElement)
document.getElementById("whatEverId").innerHTML = document.getElementById("whatEverId").innerHTML + "hello two" + document.getElementById("whatEverId").innerHTM ;
<div id="whatever">hello one</div>
<script>
document.getElementById("whatever").innerHTML += " hello two";
</script>
What jcomeau_ictx suggested is an inefficient way of editing the innerHTML. Check Ben cherry's PPT http://www.bcherry.net/talks/js-better-faster
The correct way will be detaching the element and making changes to it and then appending it back to the parent node. Use https://gist.github.com/cowboy/938767 Native javascript from this gist to detach element.