The DOM offers various methods to edit the nodes of the page and alter the document tree.
With
document.createElement()
: creates a new Element Nodedocument.createTextNode()
: creates a new Text Node
you can create new elements, and add them to the DOM elements you want as children, by using document.appendChild()
:
const div = document.createElement('div')
div.appendChild(document.createTextNode('Hello world!'))
first.removeChild(second)
removes the child node “second” from the node “first”.document.insertBefore(newNode, existingNode)
inserts “newNode” as a sibling of “existingNode”, placing it before that in the DOM tree structure.element.appendChild(newChild)
alters the tree under “element”, adding a new child Node “newChild” to it, after all the other children.element.prepend(newChild)
alters the tree under “element”, adding a new child Node “newChild” to it, before other child elements. You can pass one or more child Nodes, or even a string which will be interpreted as a Text node.element.replaceChild(newChild, existingChild)
alters the tree under “element”, replacing “existingChild” with a new Node “newChild”.element.insertAdjacentElement(position, newElement)
inserts “newElement” in the DOM, positioned relatively to “element” depending on “position” parameter value. See the possible values.element.textContent = 'something'
changes the content of a Text node to “something”.
Lessons in this unit:
0: | Introduction |
1: | The `window` object |
2: | The `document` object |
3: | Types of nodes |
4: | Traversing the DOM |
5: | ▶︎ Editing the DOM |