DOM Manipulation
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of objects; each object corresponds to a part of the document, like an element, an attribute, or a text node.
Selecting Elements
You can select elements from the DOM in various ways:
getElementById(id): Selects a single element by its ID.getElementsByTagName(tagName): Selects a collection of elements by their tag name.getElementsByClassName(className): Selects a collection of elements by their class name.querySelector(selector): Selects the first element that matches a CSS selector.querySelectorAll(selector): Selects a NodeList of all elements that match a CSS selector.
Modifying Elements
Once you have selected an element, you can modify it:
element.innerHTML: Gets or sets the HTML content within an element.element.textContent: Gets or sets the text content of an element and its descendants.element.setAttribute(name, value): Sets the value of an attribute on an element.element.style.property: Gets or sets the value of a CSS property.
Creating and Appending Elements
You can create new elements and add them to the DOM:
document.createElement(tagName): Creates a new element with the specified tag name.parentNode.appendChild(newNode): Adds a new child node to the end of the list of children of a specified parent node.parentNode.insertBefore(newNode, referenceNode): Inserts a new node before a reference node.
Removing Elements
You can remove elements from the DOM:
parentNode.removeChild(childNode): Removes a child node from the DOM.element.remove(): Removes the element from the DOM (a more modern and simpler way).