Let's suppose we have the following element on our webpage:
<div id="parent"> foobar </div>
And we want to use JavaScript to append the following HTML string to it:
const htmlStr = '<p>hello world!</p>';
How would you go about it? Let's find out:
Using insertAdjacentHTML()
We could simply use insertAdjacentHTML()
which has really good browser support. The method works by parsing the specified string as HTML (or XML) and inserts it into the DOM tree at the specified position. It has the following signature:
element.insertAdjacentHTML(position, text);
position
:
The position relative to the element
. Can be one of the following:
'beforebegin'
: Before theelement
;'afterbegin'
: Inside theelement
, before its first child;'beforeend'
: Inside theelement
, after its last child;'afterend'
: After theelement
.
Consider the following visual guide that illustrates the positioning with different options:
<!-- 'beforebegin' --> <p> <!-- 'afterbegin' --> hello world! <!-- 'beforeend' --> </p> <!-- 'afterend' -->
The beforebegin
and afterend
positions only work when the node is in the DOM tree and has a parent element.
text
:
The string to be inserted into the DOM tree.
Example:
To append the HTML string into an existing element, we could do the following:
document.getElementById('parent').insertAdjacentHTML('beforeend', htmlStr);
Using createContextualFragment()
Before we dig into details, it may be good to familiarize yourself with the following quick facts about createContextualFragment()
:
- It exists in the
Range
interface (which can be created like so:document.createRange()
); - It returns a
DocumentFragment
, which is the lightweight version ofdocument
object. The key difference betweenDocument
andDocumentFragment
is that changes made to the latter do not affect the active document (even on reflow); - Using document fragments can make DOM injections and modifications less taxing;
- It has really good browser support.
So, to append an HTML string into an existing element using createContextualFragment()
, we could do the following:
const fragment = document.createRange().createContextualFragment(htmlStr); document.getElementById('parent').appendChild(fragment);
Using innerHTML
With a Temporary Dynamic Wrapper
We could use innerHTML
on a dynamically created wrapper element, and append that to an existing element in the DOM. Consider for example:
const tempWrapper = document.createElement('div'); tempWrapper.innerHTML = htmlStr; document.getElementById('parent').appendChild(tempWrapper.firstChild);
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.