Web Analytics

Creating Elements

Intermediate ~20 min read

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.
HTML
CSS
JS

Inserting Elements

appendChild() adds the new element as the last child. To insert it somewhere else, use insertBefore().

parentNode.insertBefore(newNode, referenceNode);
HTML
CSS
JS

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).
HTML
CSS
JS

Replacing Elements

You can replace an element using replaceChild().

parentNode.replaceChild(newChild, oldChild);

Summary

  • Use createElement to make new nodes.
  • Use appendChild to add nodes to the end of a parent.
  • Use insertBefore to place nodes at specific positions.
  • Use remove to delete elements.

Quick Quiz

Which method adds a new child node to the end of the list of children of a specified parent node?

A
appendChild()
B
insertAfter()
C
addNode()
D
push()