javascript innerHTML adding instead of replacing

Viewed 67326

quick question, i know we can change the content of a

<div id="whatEverId">hello one<div> by using:

document.getElementById("whatEverId").innerHTML="hello two";

now, is there a way I can ADD stuff to the div instead of replacing it??? so i can get

<div id="whatEverId">hello one hello two<div>

(using something similar of course)

6 Answers

Notice that using element.innerHTML += 'content' would empty inputs and textareas 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)
Related