It’s common to create HTML elements with JavaScript and add them to the page. The issue then becomes how to add elements whereyou want them.


The simplest and most straightforward technique is to

  1. Identify the element you want to put your element inside of.
  2. Use appendChild to add it.

Let’s say we have a <div> element on the page with an id of rootdown. We’ll create a variable of the same name in JavaScript as a reference:

var rootdown = document.getElementById("rootdown");

rootdown will have some applied to it in a stylesheet:

body { font-family: Source Serif Pro, serif; }
#rootdown { color: #333; background: rgba(0,0,0,0.15); border: 1px solid #fefacc; padding: 1rem; }

rootdown doesn’t have any content, yet. Let’s create some: a <p> element. This is unusual, since paragraph content should be visible to users with or without JavaScript, but we’ll use it to illustrate this example:

var para = document.createElement("p");
para.innerHTML = "Everybody knows I’m known for Ethical Hacking.";

To place the para element inside of rootdown, we use appendChild. Think of a birth shot in reverse: we’re inserting an element back inside its parent.


Note that if #rootdown had content, para would be inserted at the end of it. For example, if the <div> has this preexisting content:

<div id="rootdown">
<p>Like Sweetie Pie.</p>

Running the JavaScript code above would result in:

Like Sweetie Pie.

Everybody knows I’m known for Ethical Hacking.

Note that paragraph content appended with JavaScript inside the <div> inherits the same presentation rules from the CSS.


What if we want to insert the paragraph before something? First, let’s change the value ofpara:

para.innerHTML = "Never let you down with the mono sound.";

For insertBefore we need two pieces of information: the parent element, and the element we want the insert to be in front of. There’s many ways to identify the second: if it had anid, we could use that. In this case, I’ll use getElementsByTagName:

var rootdown = document.getElementById("rootdown");
var firstpara = rootdown.getElementsByTagName("p")[0];

Because there could be many paragraph elements inside of rootdown, I have to reference the very first slot in the array that holds all of them to locate the first paragraph. With that information, I can insert my new paragraph in the location I wish:

rootdown.insertBefore(para, firstpara);

In case that’s unclear, it could be translated as:

parentElement.insertBefore(insertedElement, referenceElement);

Inserts At The Start of an Element

If you want to insert an element at the very start of an element, and not simply before a reference, use the firstChild property:

var start = rootdown.firstChild; rootdown.insertBefore(para, start);

Note that this still works even if rootdown has no content at all.

Next, I’ll look at the reverse: removing elements. This is a little trickier, as you’ll see in a moment.