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 .
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
To create DOM nodes, there are two methods:
Creates a new element node with the given tag:
let div = document.createElement('div');
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:
// 1. Create element let div = document.createElement('div'); // 2. Set its class to "alert" div.className = "alert"; // 3. Fill it with the content div.innerHTML = "Hi there! You've read an important message.";
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) .
.alert
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:
- node.append(. nodes or strings) – append nodes or strings at the end of node ,
- node.prepend(. nodes or strings) – insert nodes or strings at the beginning of node ,
- node.before(. nodes or strings) –- insert nodes or strings before node ,
- node.after(. nodes or strings) –- insert nodes or strings after node ,
- node.replaceWith(. nodes or strings) –- replaces node with the given nodes or strings.
Arguments of these methods are an arbitrary list of DOM nodes to insert, or text strings (that become text nodes automatically).
Here’s an example of using these methods to add items to a list and the text before/after it:
Here’s a visual picture of what the methods do:
So the final list will be:
As said, these methods can insert multiple nodes and text pieces in a single call.
For instance, here a string and an element are inserted:
Hello', document.createElement('hr'));
Please note: the text is inserted “as text”, not “as HTML”, with proper escaping of characters such as < , >.
In other words, strings are inserted in a safe way, like elem.textContent does it.
So, these methods can only be used to insert DOM nodes or text pieces.
But what if we’d like to insert an HTML string “as html”, with all tags and stuff working, in the same manner as elem.innerHTML does it?
insertAdjacentHTML/Text/Element
For that we can use another, pretty versatile method: elem.insertAdjacentHTML(where, html) .
The first parameter is a code word, specifying where to insert relative to elem . Must be one of the following:
- «beforebegin» – insert html immediately before elem ,
- «afterbegin» – insert html into elem , at the beginning,
- «beforeend» – insert html into elem , at the end,
- «afterend» – insert html immediately after elem .
The second parameter is an HTML string, that is inserted “as HTML”.
Hello'); div.insertAdjacentHTML('afterend', 'Bye
');
That’s how we can append arbitrary HTML to the page.
Here’s the picture of insertion variants:
We can easily notice similarities between this and the previous picture. The insertion points are actually the same, but this method inserts HTML.
The method has two brothers:
- elem.insertAdjacentText(where, text) – the same syntax, but a string of text is inserted “as text” instead of HTML,
- elem.insertAdjacentElement(where, elem) – the same syntax, but inserts an element.
They exist mainly to make the syntax “uniform”. In practice, only insertAdjacentHTML is used most of the time. Because for elements and text, we have methods append/prepend/before/after – they are shorter to write and can insert nodes/text pieces.
So here’s an alternative variant of showing a message:
.alert
Node removal
To remove a node, there’s a method node.remove() .
Let’s make our message disappear after a second:
.alert
Please note: if we want to move an element to another place – there’s no need to remove it from the old one.
All insertion methods automatically remove the node from the old place.
For instance, let’s swap elements:
Cloning nodes: cloneNode
How to insert one more similar message?
We could make a function and put the code there. But the alternative way would be to clone the existing div and modify the text inside it (if needed).
Sometimes when we have a big element, that may be faster and simpler.
- The call elem.cloneNode(true) creates a “deep” clone of the element – with all attributes and subelements. If we call elem.cloneNode(false) , then the clone is made without child elements.
An example of copying the message:
.alert Hi there! You've read an important message.
DocumentFragment
DocumentFragment is a special DOM node that serves as a wrapper to pass around lists of nodes.
We can append other nodes to it, but when we insert it somewhere, then its content is inserted instead.
return fragment; > ul.append(getListContent()); // (*)
Please note, at the last line (*) we append DocumentFragment , but it “blends in”, so the resulting structure will be:
DocumentFragment is rarely used explicitly. Why append to a special kind of node, if we can return an array of nodes instead? Rewritten example:
return result; > ul.append(. getListContent()); // append + ". " operator = friends!
We mention DocumentFragment mainly because there are some concepts on top of it, like template element, that we’ll cover much later.
Old-school insert/remove methods
There are also “old school” DOM manipulation methods, existing for historical reasons.
These methods come from really ancient times. Nowadays, there’s no reason to use them, as modern methods, such as append , prepend , before , after , remove , replaceWith , are more flexible.
The only reason we list these methods here is that you can find them in many old scripts:
Appends node as the last child of parentElem .
Inserts node before nextSibling into parentElem .
To insert newLi as the first element, we can do it like this:
list.insertBefore(newLi, list.firstChild);
Replaces oldChild with node among children of parentElem .
Removes node from parentElem (assuming node is its child).
All these methods return the inserted/removed node. In other words, parentElem.appendChild(node) returns node . But usually the returned value is not used, we just run the method.
A word about “document.write”
There’s one more, very ancient method of adding something to a web-page: document.write .
Somewhere in the page.
The end
The call to document.write(html) writes the html into page “right here and now”. The html string can be dynamically generated, so it’s kind of flexible. We can use JavaScript to create a full-fledged webpage and write it.
The method comes from times when there was no DOM, no standards… Really old times. It still lives, because there are scripts using it.
In modern scripts we can rarely see it, because of the following important limitation:
The call to document.write only works while the page is loading.
If we call it afterwards, the existing document content is erased.
After one second the contents of this page will be replaced.
So it’s kind of unusable at “after loaded” stage, unlike other DOM methods we covered above.
There’s an upside also. Technically, when document.write is called while the browser is reading (“parsing”) incoming HTML, and it writes something, the browser consumes it just as if it were initially there, in the HTML text.
So it works blazingly fast, because there’s no DOM modification involved. It writes directly into the page text, while the DOM is not yet built.
So if we need to add a lot of text into HTML dynamically, and we’re at page loading phase, and the speed matters, it may help. But in practice these requirements rarely come together. And usually we can see this method in scripts just because they are old.
Summary
- Methods to create new nodes:
- document.createElement(tag) – creates an element with the given tag,
- document.createTextNode(value) – creates a text node (rarely used),
- elem.cloneNode(deep) – clones the element, if deep==true then with all descendants.
- node.append(. nodes or strings) – insert into node , at the end,
- node.prepend(. nodes or strings) – insert into node , at the beginning,
- node.before(. nodes or strings) –- insert right before node ,
- node.after(. nodes or strings) –- insert right after node ,
- node.replaceWith(. nodes or strings) –- replace node .
- node.remove() –- remove the node .
Text strings are inserted “as text”.
- parent.appendChild(node)
- parent.insertBefore(node, nextSibling)
- parent.removeChild(node)
- parent.replaceChild(newElem, node)
All these methods return node .
- «beforebegin» – insert html right before elem ,
- «afterbegin» – insert html into elem , at the beginning,
- «beforeend» – insert html into elem , at the end,
- «afterend» – insert html right after elem .
Also there are similar methods, elem.insertAdjacentText and elem.insertAdjacentElement , that insert text strings and elements, but they are rarely used.
After the page is loaded such a call erases the document. Mostly seen in old scripts.
Tasks
createTextNode vs innerHTML vs textContent
We have an empty DOM element elem and a string text .
Which of these 3 commands will do exactly the same?
- elem.append(document.createTextNode(text))
- elem.innerHTML = text
- elem.textContent = text
Answer: 1 and 3.
Both commands result in adding the text “as text” into the elem .