Modifying the DOM
We can move elements around like so:
// Append element1 as the last child of element2
element1.appendChild(element2)
// Insert element2 as child of element 1, right before element3
element1.insertBefore(element2, element3)
If we don’t want to move the element, but insert a copy, we can clone it like so:
// Create a clone
const myElementClone = myElement.cloneNode()
myParentElement.appendChild(myElementClone)
The.cloneNode()
method optionally takes a boolean as argument; if set to true, a deep copy will be created, meaning its children are also cloned.
Of course, we can just as well create entirely new elements or text nodes:
const myNewElement = document.createElement('div')
const myNewTextNode = document.createTextNode('some text')
which we can then insert as shown above. If we want to remove an element, we can’t do so directly, but we_can_remove children from a parent element, like so:
myParentElement.removeChild(myElement)
This gives us a nice little work around, meaning can actually remove an element indirectly, by referencing its parent element:
myElement.parentNode.removeChild(myElement)