clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Append and prepend elements with pure JavaScript

Filed under: JavaScript— Tagged with: DOM

Adding element after and before other elements in the DOM, also known as appending or prepending. Pure JavaScript provides some handy methods for that.

If you’ve used jQuery, you might know append() and prepend() methods, here’s how to do that with native JavaScript.

Appending elements with appendChild

The appendChild method will put the source element inside the target element, in the last position, after all of the pre-existing elements.

The below example will:

  1. Get en existing element #box
  2. Create a new element and store it into a variable jack
  3. Give the new element some content
  4. And put the jack in the #box
const box = document.getElementById('box')
const jack = document.createElement('div')
jack.innerHTML = 'Jack!'
box.appendChild(jack)

That would give us the following HTML:

<div id="box">
  <p>Lorem ipsum...</p>
  <div>Jack!</div>
</div>

There’s a rule: the same node can’t be present twice in the DOM, this means that if an existing element is appended, it will be removed from it’s original position. So in that case it’s more like a move command. If this is not desired, try the .cloneNode() instead.

Prepend with insertBefore

There’s no prependChild, but prepending can be done using the insertBefore().

The steps are the same as above, expect the last line. You need to give insertBefore 3 things:

  1. The target element to insert: box
  2. What to insert: jack
  3. Before which element to insert: element.firstChild
const box = document.getElementById('box')
const jack = document.createElement('div')
jack.innerHTML = 'Jack!'
box.insertBefore(jack, box.firstChild)

Demo

Performance compared to jQuery

Performance is of course completely unimportant, unless you deal with millions of iterations. But anyway, the native methods are much faster than jQuery .append().

Higher the dongle === faster:

A screenshot of JSPerf bar graph.
Test from JSPerf, generated at 2015-04-17

Conclusions

Both of these methods are pretty solid and they work in all browsers.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!