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

  • Anonymous says:

    This site looks like shit.

  • anon says:

    This comment looks like shit

  • The P Love says:

    Cool, thanks for this. Fuck jQuery right? Slow and bloated. The more pure javascript the better!

  • The P Love says:

    Was able to use this snippet to build a pure CSS / Javascript fade image slider. http://codepen.io/palmerlovett/pen/mPRZvV

  • Nell says:

    Love the performance review between javaScript and jQuery ! :D
    Speed always wins over huge library load times . Glad I found this helpful article. ;)

  • Sher says:

    Hooray! The other javascript only solutions were not this clear and concise. Trying to be jquery free.

  • Sam says:

    Hey thanks! The documentation was clear and concise with some background research as well :)

    VERY out of this world layout and color scheme. Do you bro. Do you.

  • Anonymous says:

    followed on twitter, love the site.

  • Schizo says:

    jQuery.append, yet, is more power than the Wep API

    What aboud append element with a string
    You can not update the entire innerHTML because you will lose event listeners

    $(‘body’).append(‘

    Elem 1

    Elem 2’);

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