JS: DOM API
Theory: Manipulating the Dom tree
A DOM tree can change when the browser has already been rendered it. This fact provides a key opportunity for creating interactive applications. In this lesson, we will discuss how to manipulate DOM trees and what features we can get by doing so.
innerHTML
The easiest way to update a part of a DOM tree is the innerHTML property:
The value of this property completely replaces the descendants of the element on which we have called it. All the HTML found inside is analyzed and becomes part of the tree.
Imagine we try to insert plain text with a potential HTML in it. It raises the possibility of XSS attacks, so we should use a different property – textContent.
The property textContent works almost identically, it replaces all descendants, too. The main difference between these properties is that textContent treats its content as plain text anyway, even if there's HTML:
The property innerHTML works with strings, which is only convenient if we're working with a static DOM representation. There are special functions suitable for generating a DOM tree dynamically.
Creating nodes
When the code creates a DOM dynamically, it looks like a nesting doll. Once created, some elements are put into others all the time. The code that creates trees will look like this in any language.
Insert
ParentNode.prepend() adds the nodes passed by the first child to ParentNode:
ParentNode.append() adds the nodes passed by the last child to ParentNode:
childNode.before(...nodes) inserts nodes into the list of children of the parent node of this childNode right before the childNode itself:
childNode.after(...nodes) – inserts nodes into the list of children of the parent node of this childNode immediately after it:
node.replaceWith(...nodes) replaces a single node with multiple ones. The node itself disappears from the DOM tree, but it remains available in the code:
node.remove() removes the current node.
Old API
The functions described above only appeared lately. Before that, programmers wrote most of the code using the other functions listed below:
parent.appendChild(el)– addselto the end of the list of childrenparent.insertBefore(el, nextElSibling)– addselto the list of children of aparentbefore thenextElSiblingparent.removeChild(el)– removeselfrom the children of aparentparent.replaceChild(newEl, el)– replaceselwithnewEl
Cloning
Sometimes, you need to create an element similar to an existing one. Of course, you can do this 100% manually by copying the properties of one into the properties of another. But there's an easier way:
The value true shows that we make a deep copy, meaning a copy of that element with all its descendants.

