Append and prepend elements with pure JavaScript

Prepending and appending stuff in pure JavaScript is fast and effortless.

Appending is not hard at all, there is an appendChild() method in JavaScript. Prepending an element is a bit harder but not really.

Append

The following will create a new element and jug it into an existing element:

// Grab an element
var el = document.getElementById('thingy'),
    // Make a new div
    elChild = document.createElement('div');

// Give the new div some content
elChild.innerHTML = 'Content';

// Jug it into the parent element
el.appendChild(elChild);

The same node can’t be present twice in the DOM, so if an existing element is appended, it’ll be removed from it’s original position. If this is not desired, try the .cloneNode().

MDN article on appendChild

Prepend

For prepending insertBefore() method needs to be used:

var el = document.getElementById('thingy'),
    elChild = document.createElement('div');
elChild.innerHTML = 'Content';

// Prepend it
el.insertBefore(elChild, el.firstChild);

MDN article on insertBefore

Demo

JS Bin

Performance compared to jQuery

The performance is breathtaking compared to jQuery’s .append() method, higher the dongle the better it is:

Test from JSPerf
Test from JSPerf

Conclusions

Both of these methods work in all browsers. As I learn more and more native JavaScript it apparent that jQuery is not so necessary always.

Comments

Club-Mate, the beverage → club-mate.fi