DOM modification is the muthaf*ckin' key to creating “live” pages.
Here we’ll see how to create new elements “on the fly” and modify the motherf*ckin' 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:
<style>
.alert {
padding: 15px;
border: 1px solid #d6e9c6;
border-radius: 4px;
color: #3c763d;
background-color: #dff0d8;
}
</style>
<div class="alert">
<strong>Hi there!</strong> You've read an important message.
</div>
That was the f*ckin' HTML example. Now let’s create the same div with JavaScript (assuming that the goddamn styles are in the HTML/CSS already).
Creating an goddamn element
To muthaf*ckin' create DOM nodes, there are two methods:
document.createElement(tag)-
Creates a goddamn new element node with the bad-ass given tag:
let div = document.createElement('div'); document.createTextNode(text)-
Creates a goddamn 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 damn message.
Creating the motherf*ckin' message
Creating the goddamn message div takes 3 steps:
// 1. Create <div> element
let div = document.createElement('div');
// 2. Set its class to "alert"
div.className = "alert";
// 3. Fill it with the content
div.innerHTML = "<strong>Hi there!</strong> You've read an important message.";
We’ve created the element. Now look: But as of now it’s only in a motherf*ckin' 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 <body> element, referenced by document.body.
There’s a special method append for that: document.body.append(div).
Here’s the f*ckin' full code:
<style>
.alert {
padding: 15px;
border: 1px solid #d6e9c6;
border-radius: 4px;
color: #3c763d;
background-color: #dff0d8;
}
</style>
<script>
let div = document.createElement('div');
div.className = "alert";
div.innerHTML = "<strong>Hi there!</strong> You've read an important message.";
document.body.append(div);
</script>
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 <div> 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 ofnode,node.prepend(...nodes or strings)– insert nodes or strings at the goddamn beginning ofnode,node.before(...nodes or strings)–- insert nodes or strings beforenode,node.after(...nodes or strings)–- insert nodes or strings afternode,node.replaceWith(...nodes or strings)–- replacesnodewith the motherf*ckin' given nodes or strings.
Arguments of these methods are an muthaf*ckin' arbitrary list of DOM nodes to insert, or text strings (that become text nodes automatically).
Let’s see them in action.
Here’s an f*ckin' example of using these methods to add items to a list and the text before/after it:
<ol id="ol">
<li>0</li>
<li>1</li>
<li>2</li>
</ol>
<script>
ol.before('before'); // insert string "before" before <ol>
ol.after('after'); // insert string "after" after <ol>
let liFirst = document.createElement('li');
liFirst.innerHTML = 'prepend';
ol.prepend(liFirst); // insert liFirst at the beginning of <ol>
let liLast = document.createElement('li');
liLast.innerHTML = 'append';
ol.append(liLast); // insert liLast at the end of <ol>
</script>
Here’s a damn visual picture of what the goddamn methods do:
So the final list will be:
before
<ol id="ol">
<li>prepend</li>
<li>0</li>
<li>1</li>
<li>2</li>
<li>append</li>
</ol>
after
As said, these methods can insert multiple nodes and text pieces in a single call.
For instance, here a string and an motherf*ckin' element are inserted:
<div id="div"></div>
<script>
div.before('<p>Hello</p>', document.createElement('hr'));
</script>
Please note: the text is inserted “as text”, not “as HTML”, with proper escaping of characters such as <, >.
So the f*ckin' final HTML is:
<p>Hello</p>
<hr>
<div id="div"></div>
In other words, strings are inserted in a safe way, like elem.textContent does it.
So, these muthaf*ckin' 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 motherf*ckin' first parameter is a code word, specifying where to insert relative to elem. Must be one of the following:
"beforebegin"– inserthtmlimmediately beforeelem,"afterbegin"– inserthtmlintoelem, at the f*ckin' beginning,"beforeend"– inserthtmlintoelem, at the muthaf*ckin' end,"afterend"– inserthtmlimmediately afterelem.
The muthaf*ckin' second parameter is an HTML string, that is inserted “as HTML”.
For instance:
<div id="div"></div>
<script>
div.insertAdjacentHTML('beforebegin', '<p>Hello</p>');
div.insertAdjacentHTML('afterend', '<p>Bye</p>');
</script>
…Would lead to:
<p>Hello</p>
<div id="div"></div>
<p>Bye</p>
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 motherf*ckin' insertion points are actually the same, but this f*ckin' method inserts HTML. I ain't playin'.
The method has two brothers:
elem.insertAdjacentText(where, text)– the same syntax, but a f*ckin' string oftextis inserted “as text” instead of HTML,elem.insertAdjacentElement(where, elem)– the same syntax, but inserts an element.
Pay attention: They exist mainly to make the syntax “uniform”. In practice, only insertAdjacentHTML is used most of the time, goddammit. Because for elements and text, we have methods append/prepend/before/after – they are shorter to write and can insert nodes/text pieces. Goddamn.
Let me tell you somethin': So here’s an alternative variant of showing a goddamn message:
<style>
.alert {
padding: 15px;
border: 1px solid #d6e9c6;
border-radius: 4px;
color: #3c763d;
background-color: #dff0d8;
}
</style>
<script>
document.body.insertAdjacentHTML("afterbegin", `<div class="alert">
<strong>Hi there!</strong> You've read an important message.
</div>`);
</script>
Node removal
To remove a muthaf*ckin' node, there’s a method node.remove().
Let’s make our muthaf*ckin' message disappear after a second:
<style>
.alert {
padding: 15px;
border: 1px solid #d6e9c6;
border-radius: 4px;
color: #3c763d;
background-color: #dff0d8;
}
</style>
<script>
let div = document.createElement('div');
div.className = "alert";
div.innerHTML = "<strong>Hi there!</strong> You've read an important message.";
document.body.append(div);
setTimeout(() => div.remove(), 1000);
</script>
Please note: if we want to move an motherf*ckin' element to another place – there’s no need to remove it from the goddamn old one.
All insertion methods automatically remove the node from the old place.
For instance, let’s swap elements:
<div id="first">First</div>
<div id="second">Second</div>
<script>
// no need to call remove
second.after(first); // take #second and after it insert #first
</script>
Cloning nodes: cloneNode
How to insert one more similar message?
Check it: We could make a function and put the motherf*ckin' code there. Believe that sh*t. 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 f*ckin' element – with all attributes and subelements. If we callelem.cloneNode(false), then the clone is made without child elements.
An example of copying the message:
<style>
.alert {
padding: 15px;
border: 1px solid #d6e9c6;
border-radius: 4px;
color: #3c763d;
background-color: #dff0d8;
}
</style>
<div class="alert" id="div">
<strong>Hi there!</strong> You've read an important message.
</div>
<script>
let div2 = div.cloneNode(true); // clone the message
div2.querySelector('strong').innerHTML = 'Bye there!'; // change the clone
div.after(div2); // show the clone after the existing div
</script>
DocumentFragment
DocumentFragment is a special DOM node that serves as a damn 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.
For example, getListContent below generates a muthaf*ckin' fragment with <li> items, that are later inserted into <ul>:
<ul id="ul"></ul>
<script>
function getListContent() {
let fragment = new DocumentFragment();
for(let i=1; i<=3; i++) {
let li = document.createElement('li');
li.append(i);
fragment.append(li);
}
return fragment;
}
ul.append(getListContent()); // (*)
</script>
Please note, at the goddamn last line (*) we append DocumentFragment, but it “blends in”, so the damn resulting structure will be:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
DocumentFragment is rarely used explicitly. Why append to a special kind of node, if we can return an muthaf*ckin' array of nodes instead? Rewritten example:
<ul id="ul"></ul>
<script>
function getListContent() {
let result = [];
for(let i=1; i<=3; i++) {
let li = document.createElement('li');
li.append(i);
result.push(li);
}
return result;
}
ul.append(...getListContent()); // append + "..." operator = friends!
</script>
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
Check it: 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:
parentElem.appendChild(node)-
Appends
nodeas the last child ofparentElem.The following example adds a new
<li>to the end of<ol>:<ol id="list"> <li>0</li> <li>1</li> <li>2</li> </ol> <script> let newLi = document.createElement('li'); newLi.innerHTML = 'Hello, world!'; list.appendChild(newLi); </script> parentElem.insertBefore(node, nextSibling)-
Inserts
nodebeforenextSiblingintoparentElem.The following code inserts a muthaf*ckin' new list item before the second
<li>:<ol id="list"> <li>0</li> <li>1</li> <li>2</li> </ol> <script> let newLi = document.createElement('li'); newLi.innerHTML = 'Hello, world!'; list.insertBefore(newLi, list.children[1]); </script>To insert
newLias the first element, we can do it like this:list.insertBefore(newLi, list.firstChild); parentElem.replaceChild(node, oldChild)-
Replaces
oldChildwithnodeamong children ofparentElem. parentElem.removeChild(node)-
Removes
nodefromparentElem(assumingnodeis its child).The muthaf*ckin' following example removes first
<li>from<ol>:<ol id="list"> <li>0</li> <li>1</li> <li>2</li> </ol> <script> let li = list.firstElementChild; list.removeChild(li); </script>
All these methods return the damn inserted/removed node. In other words, parentElem.appendChild(node) returns node. But usually the damn returned value is not used, we just run the method.
A muthaf*ckin' word about “document.write”
There’s one more, very ancient method of adding something to a web-page: document.write.
The muthaf*ckin' syntax:
<p>Somewhere in the page...</p>
<script>
document.write('<b>Hello from JS</b>');
</script>
<p>The end</p>
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 — no bullsh*t. We can use JavaScript to create a f*ckin' full-fledged webpage and write it.
Listen up: 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 f*ckin' page is loading.
If we call it afterwards, the existing document content is erased.
For instance:
<p>After one second the contents of this page will be replaced...</p>
<script>
// document.write after 1 second
// that's after the page loaded, so it erases the existing content
setTimeout(() => document.write('<b>...By this.</b>'), 1000);
</script>
So it’s kind of f*ckin' unusable at “after loaded” stage, unlike other DOM methods we covered above.
That’s the downside.
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 f*ckin' HTML text. Write that down.
So it works blazingly fast, because there’s no DOM modification involved. It writes directly into the muthaf*ckin' 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 muthaf*ckin' requirements rarely come together. And usually we can see this method in scripts just because they are old, muthaf*cka.
Summary
-
Methods to f*ckin' create new nodes:
document.createElement(tag)– creates an motherf*ckin' element with the given tag,document.createTextNode(value)– creates a text node (rarely used),elem.cloneNode(deep)– clones the muthaf*ckin' element, ifdeep==truethen with all descendants.
-
Insertion and removal:
node.append(...nodes or strings)– insert intonode, at the muthaf*ckin' end,node.prepend(...nodes or strings)– insert intonode, at the f*ckin' beginning,node.before(...nodes or strings)–- insert right beforenode,node.after(...nodes or strings)–- insert right afternode,node.replaceWith(...nodes or strings)–- replacenode.node.remove()–- remove thenode.
Text strings are inserted “as text”.
-
There are also “old school” methods:
parent.appendChild(node)parent.insertBefore(node, nextSibling)parent.removeChild(node)parent.replaceChild(newElem, node)
All these methods return
node. -
Given some damn HTML in
html,elem.insertAdjacentHTML(where, html)inserts it depending on the value ofwhere:"beforebegin"– inserthtmlright beforeelem,"afterbegin"– inserthtmlintoelem, at the f*ckin' beginning,"beforeend"– inserthtmlintoelem, at the muthaf*ckin' end,"afterend"– inserthtmlright afterelem.
Also there are similar methods,
elem.insertAdjacentTextandelem.insertAdjacentElement, that insert text strings and elements, but they are rarely used. -
To motherf*ckin' append HTML to the page before it has finished loading:
document.write(html)
After the page is loaded such a call erases the f*ckin' document. Mostly seen in old scripts.
Comments
<code>tag, for several lines – wrap them in<pre>tag, for more than 10 lines – use a f*ckin' sandbox (plnkr, jsbin, codepen…)