Evaluating Strategies for Appending and Inserting With JavaScript

No Comments

Let’s say we need to add one thing to a webpage after the preliminary load. JavaScript offers us a wide range of instruments. Maybe you’ve used a few of them, like append, appendChild, insertAdjacentHTML, or innerHTML.

The troublesome factor about appending and inserting issues with JavaScript isn’t a lot in regards to the instruments it gives, however which one to make use of, when to make use of them, and understanding how each works.

Let’s attempt to clear issues up.

Tremendous fast context

It is perhaps useful to debate a bit background earlier than leaping in. On the easiest stage, an internet site is an HTML file downloaded from a server to a browser.

Your browser converts the HTML tags inside your HTML file right into a bunch of objects that may be manipulated with JavaScript. These objects assemble a Doc Object Mannequin (DOM) tree. This tree is a collection of objects which are structured as parent-child relationships.

In DOM parlance, these objects are known as nodes, or extra particularly, HTML components.

<!– I am the mum or dad factor –>
<!– I am a baby factor –>
<span>Good day</span>

On this instance, the HTML span factor is the baby of the div factor, which is the mum or dad.

And I do know that a few of these phrases are bizarre and probably complicated. We are saying “node”, however different occasions we could say “factor” or “object” as a substitute. And, in some circumstances, they check with the identical factor, simply relying on how particular we need to be .

For instance, an “factor” is a selected sort of “node”, similar to an apple is a selected sort of fruit.

We are able to arrange these phrases from most normal, to most particular: ObjectNodeComponentHTML Component

Understanding these DOM objects is vital, as we’ll work together with them so as to add and append issues with JavaScript after an preliminary web page load. The truth is, let’s begin engaged on that.


These append and insert strategies largely observe this sample:


Once more, a component is merely an object within the DOM Tree that represents some HTML. Earlier, we had talked about that the aim of the DOM tree is to provide us a handy strategy to work together with HTML utilizing JavaScript.

So, how can we use JavaScript to seize an HTML factor?

Querying the DOM

Let’s say now we have the next tiny little bit of HTML:

<div id=”instance” class=”group”>
Good day World

There are a couple of widespread methods to question the DOM:

// Question a selected selector (could possibly be class, ID, factor sort, or attribute):
const my_element1 = doc.querySelector(‘#instance’)

// Question a component by its ID:
const my_element2 = doc.getElementbyId(‘instance’)

// Question a component by its class:
const my_element3 = doc.getElementbyClass(‘group’)[0]

On this instance, all three traces question the identical factor, however search for it in numerous methods. One seems at any of the merchandise’s CSS selectors; one seems on the merchandise’s ID; and one seems on the merchandise’s class.

Word that the getElementbyClass methodology returns an array. That’s as a result of it’s able to matching a number of components within the DOM and storing these matches in an array makes positive all of them are accounted for.

What we will append and insert

// Append One thing
const my_element1 = doc.querySelector(‘#instance’)
my_element1.append(one thing)

On this instance, one thing is a parameter that represents stuff we need to tack on to the tip of (i.e. append to) the matched factor.

We are able to’t simply append any outdated factor to any outdated object. The append methodology solely permits us to append both a node or plain textual content to a component within the DOM. However another strategies can append HTML to DOM components as properly.

Nodes are both created with doc.createElement() in JavaScript, or they’re chosen with one of many question strategies we checked out within the final part.Plain textual content is, properly, textual content. It’s plain textual content in that it doesn’t carry any HTML tags or formatting with it. (e.g. Good day).HTML can also be textual content however, not like plain textual content, it does certainly get parsed as markup when it’s added to the DOM (e.g. <div>Good day</div>).

It’d assist to map out precisely which parameters are supported by which strategies:

MethodNodeHTML TextTextappendYesNoYesappendChildYesNoNoinsertAdjacentHTMLNoYesYes1innerHTML2NoYesYes1 This works, however insertAdjacentText is advisable.
2 As an alternative of taking conventional parameters, innerHTML is used like: factor.innerHTML = ‘HTML String’

How to decide on which methodology to make use of

Properly, it actually will depend on what you’re trying to append, to not point out sure browser quirks to work round.

When you’ve got current HTML that will get despatched to your JavaScript, it’s in all probability best to work with strategies that assist HTML.If you happen to’re constructing some new HTML in JavasScript, making a node with heavy markup may be cumbersome, whereas HTML is much less verbose.If you wish to connect occasion listeners immediately, you’ll need to work with nodes as a result of we name addEventListener on nodes, not HTML.If all you want is textual content, any methodology supporting plain textual content parameters is ok.In case your HTML is doubtlessly untrustworthy (i.e. it comes from consumer enter, say a touch upon a weblog put up), you then’ll need to watch out when utilizing HTML, until it has been sanitized (i.e. the dangerous code has been eliminated).If you must assist Web Explorer, then utilizing append is out of the query.


Let’s say now we have a chat software, and we need to append a consumer, Dale, to a buddy checklist once they log in.

<!– HTML Buddy Checklist –>
<ul id=”buddies”>
<!– Append subsequent consumer right here –>

Right here’s how we’d accomplish this utilizing every of the strategies above.


We have to create a node object that interprets to <li><a>Dale</a></li>.

const new_buddy = doc.createElement(‘li’)
const new_link = doc.createElement(‘a’)

const buddy_name = “Dale”

new_link.append(buddy_name) // Textual content param
new_buddy.append(new_link) // Node param

const checklist = doc.querySelector(‘#buddies’)
checklist.append(new_buddy) // Node param

Our ultimate append locations the brand new consumer on the finish of the buddy checklist, simply earlier than the closing </ul> tag. If we’d want to put the consumer on the entrance of the checklist, we may use the prepend methodology as a substitute.

You might have seen that we have been additionally ready to make use of append to fill our <a> tag with textual content like this:

const buddy_name = “Dale”
new_link.append(buddy_name) // Textual content param

This highlights the flexibility of append.

And simply to name it out as soon as extra, append is unsupported in Web Explorer.


appendChild is one other JavaScript methodology now we have for appending stuff to DOM components. It’s a bit restricted in that it solely works with node objects, so we we’ll want some assist from textContent (or innerText) for our plain textual content wants.

Word that appendChild, not like append, is supported in Web Explorer.

const new_buddy = doc.createElement(‘li’)
const new_link = doc.createElement(‘a’)

const buddy_name = “Dale”

new_link.textContent = buddy_name
new_buddy.appendChild(new_link) // Node param

const checklist = doc.querySelector(‘#buddies’)
checklist.appendChild(new_buddy) // Node param

Earlier than shifting on, let’s contemplate an identical instance, however with heavier markup.

Let’s say the HTML we needed to append didn’t appear like <li><a>Dale</a></li>, however quite:

<li class=”abc” data-tooltip=”Click on for Dale”>
<a id=”user_123″ class=”def” data-user=”dale”>
<img src=”photographs/dale.jpg” alt=”Profile Image”/>

Our JavaScript would look one thing like:

const buddy_name = “Dale”

const new_buddy = doc.createElement(‘li’)
new_buddy.className = (‘abc’)
new_buddy.setAttribute(‘data-tooltip’, `Click on for ${buddy_name}`)

const new_link = doc.createElement(‘a’)
new_link.id = ‘user_123’
new_link.className = (‘def’)
new_link.setAttribute(‘data-user’, buddy_name)

const new_profile_img = doc.createElement(‘img’)
new_profile_img.src = ‘photographs/dale.jpg’
new_profile_img.alt = ‘Profile Image’

const new_buddy_span = doc.createElement(‘span’)
new_buddy_span.textContent = buddy_name

new_link.appendChild(new_profile_img) // Node param
new_link.appendChild(new_buddy_span) // Node param
new_buddy.appendChild(new_link) // Node param

const checklist = doc.querySelector(‘#buddies’)
checklist.appendChild(new_buddy) // Node param

There’s no must observe all of above JavaScript – the purpose is that creating giant quantities of HTML in JavaScript can develop into fairly cumbersome. And there’s no getting round this if we use append or appendChild.

On this heavy markup situation, it is perhaps good to only write our HTML as a string, quite than utilizing a bunch of JavaScript strategies…


insertAdjacentHTML is is like append in that it’s additionally able to including stuff to DOM components. One distinction, although, is that insertAdjacentHTML inserts that stuff at a selected place relative to the matched factor.

And it simply so occurs to work with HTML. Meaning we will insert precise HTML to a DOM factor, and pinpoint precisely the place we would like it with 4 completely different positions:

<!– beforebegin –>
<div id=”instance” class=”group”>
<!– afterbegin –>
Good day World
<!– beforeend –>
<!– afterend –>

So, we will sorta replicate the identical thought of “appending” our HTML by inserting it on the beforeend place of the #buddies selector:

const buddy_name = “Dale”

const new_buddy = `<li><a>${buddy_name}</a></li>`
const checklist = doc.querySelector(‘#buddies’)
checklist.insertAdjacentHTML(‘beforeend’, new_buddy)

Keep in mind the safety issues we talked about earlier. We by no means need to insert HTML that’s been submitted by an finish consumer, as we’d open ourselves as much as cross-site scripting vulnerabilities.


innerHTML is one other methodology for inserting stuff. That stated, it’s not advisable for inserting, as we’ll see.

Right here’s our question and the HTML we need to insert:

const buddy_name = “Dale”
const new_buddy = `<li><a>${buddy_name}</a></li>`
const checklist = doc.querySelector(‘#buddies’)
checklist.innerHTML += new_buddy

Initially, this appears to work. Our up to date buddy checklist seems like this within the DOM:

<ul id=”buddies”>

That’s what we would like! However there’s a constraint with utilizing innerHTML that stops us from utilizing occasion listeners on any components within #buddies due to the character of += in checklist.innerHTML += new_buddy.

You see, A += B behaves the identical as A = A + B. On this case, A is our current HTML and B is what we’re inserting to it. The issue is that this ends in a duplicate of the prevailing HTML with the extra inserted HTML. And occasion listeners are unable to hearken to copies. Meaning if we need to pay attention for a click on occasion on any of the <a> tags within the buddy checklist, we’re going to lose that capability with innerHTML.

So, only a phrase of warning there.


Right here’s a demo that pulls collectively the entire strategies we’ve lined. Clicking the button of every methodology inserts “Dale” as an merchandise within the buddies checklist.

CodePen Embed Fallback

Go forward and open up DevTools when you’re at it and see how the brand new checklist merchandise is added to the DOM.


Right here’s a normal overview of the place we stand once we’re appending and inserting stuff into the DOM. Take into account it a cheatsheet for while you need assistance determining which methodology to make use of.

HTML TextText
Web Explorer?Occasion ListenersSecure?
HTML TemplatingappendYesNoYesNoPreservesYesMediumappendChildYesNoNoYesPreservesYesMediuminsertAdjacentHTMLNoYesYes1YesPreservesCarefulEasyinnerHTML2NoYesYesYesLosesCarefulEasy1 This works, however insertAdjacentText is advisable.
2 As an alternative of taking conventional parameters, innerHTML is used like: factor.innerHTML = ‘HTML String’

If I needed to condense all of that into a couple of suggestions:

Utilizing innerHTML for appending is just not advisable because it removes occasion listeners.append works properly if you happen to like the pliability of working with node components or plain textual content, and don’t must assist Web Explorer.appendChild works properly if you happen to like (or want) to work with node components, and wish full browser protection.insertAdjacentHTML is sweet if you must generate HTML, and need to extra particular management over the place it’s positioned within the DOM.

Final thought and a fast plug 🙂

This put up was impressed by actual points I just lately bumped into when constructing a chat software. As you’d think about, a chat software depends on quite a lot of appending/inserting — folks coming on-line, new messages, notifications, and so on.

That chat software known as Bounce. It’s a peer-to-peer studying chat. Assuming you’re a JavaScript developer (amongst different issues), you in all probability have one thing to show! And you may earn some additional money.

If you happen to’re curious, right here’s a hyperlink to the homepage, or my profile on Bounce. Cheers!

The put up Evaluating Strategies for Appending and Inserting With JavaScript appeared first on CSS-Methods. You’ll be able to assist CSS-Methods by being an MVP Supporter.

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment