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
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
- you may feel compelled to add an
idto the element, but it’s unlikely that you need to do so: you already have a reference to the element in the
- 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
insertAdjacentHTML are the same, but there are significant differences. Most importantly,
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.