Creating Elements
Creating New Elements
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
document.createElement(tag): Creates a new element node.document.createTextNode(text): Creates a new text node.element.appendChild(node): Appends a node as the last child of a node.
Inserting Elements
appendChild() adds the new element as the
last child. To insert it somewhere else, use
insertBefore().
parentNode.insertBefore(newNode, referenceNode);
Removing Elements
To remove an HTML element, use remove() or
removeChild().
element.remove(): Removes the element itself (Modern).parent.removeChild(child): Removes a child node from the parent (Legacy/Cross-browser).
Replacing Elements
You can replace an element using replaceChild().
parentNode.replaceChild(newChild, oldChild);
Summary
- Use
createElementto make new nodes. - Use
appendChildto add nodes to the end of a parent. - Use
insertBeforeto place nodes at specific positions. - Use
removeto delete elements.
Quick Quiz
Which method adds a new child node to the end of the list of children of a specified parent node?
Enjoying these tutorials?