You can use element.insertAdjacentHTML()
to evaluate and append a raw HTML string to an element.
element.insertAdjacentHTML('beforeend', '<p>put me inside at the end</p>');
By changing the position
attribute you can insert before the element, after it, inside it at the beginning, or inside it at the end.
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
Unlike innerHTML
, insertAdjacentHTML()
won't cause the browser won't to re-evaluate the entire DOM node you're injecting into, so form field values will be maintained.
var parentEl = document.getElementById('parent');
parentEl.insertAdjacentHTML('beforeend', '<p>this paragraph was inserted at the end of the form without affecting the form field values!<p>');
<form id="parent">
<input type="text" value="insert something after form"><br>
<input type="text" value="without affecting the values"><br>
<input type="text" value="in the form fields"><br>
</form>