Photograph of a green leaf floating above a male hand

While developers should keep to the ideals of progressive development as much as possible when using JavaScript, there are absolutely times that we must create elements ex nihilo. Often these are elements that depend on JavaScript for their functionality, and therefore should be created with JavaScript:

The Summoning

We can create any kind of HTML element using document.createElement and the tag name:

var newAside = document.createElement("aside");

At this point, the element is simply floating in the aether: it’s not yet part of our page. There are many ways of doing just that, but perhaps the easiest is using appendChild:

document.body.appendChild(newAside);

There are a few things to note:

  • you can’t currently add an attribute to the element at the same moment it is created; you must use setAttribute or a related method on a separate line of JavaScript.
  • you may feel compelled to add an id to the element, but it’s unlikely that you need to do so: you already have a reference to the element in the newAside variable.
  • once you add it to the page, the new element will follow any presentation rules applied to it via a CSS stylesheet.

What’s the difference between this and insertAdjacentHTML?

Since they both ultimately achieve the same ends of putting elements on a page, it might be tempting to believe that document.createElement and insertAdjacentHTML are the same, but there are significant differences. Most importantly, insertAdjacentHTML takes a string of characters that JavaScript parses into HTML, whereas document.createElement creates a node with a variable that can be referenced later.

Photograph by Sherman Geronimo-Tan, used under a Creative Commons Attribution 2.0 Generic License

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.