Back to Home

Modifying the document

DOM modification is the key to creating “live” pages. Here we’ll see how to create new elements “on the fly” and modify the existing page content.

Example: show a message

Let’s demonstrate using an example. We’ll add a message on the page that looks nicer than alert. Here’s how it will look: That was the HTML example. Now let’s create the same div with JavaScript (assuming that the styles are in the HTML/CSS already).

Creating an element

document.createElement(tag)

Creates a new element node with the given tag:


let div = document.createElement('div');
document.createTextNode(text)

Creates a new text node with the given text:

let textNode = document.createTextNode('Here I am');

Most of the time we need to create element nodes, such as the div for the message.

Creating the message

Creating the message div takes 3 steps: We’ve created the element. But as of now it’s only in a variable named div, not in the page yet. So we can’t see it.

Insertion methods

To make the div show up, we need to insert it somewhere into document. For instance, into element, referenced by document.body. There’s a special method append for that: document.body.append(div). Here’s the full code: Here we called append on document.body, but we can call append method on any other element, to put another element into it. For instance, we can append something to

by calling div.append(anotherElement). Here are more insertion methods, they specify different places where to insert: