DOM Manipulation
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM is a tree-like structure, where each node represents a part of the document, such as an element, attribute, or text.
Understanding the DOM
When a web page is loaded, the browser creates a DOM representation of that page. This DOM can be modified using JavaScript, allowing for dynamic changes to the web page without requiring a full page reload.
Key Concepts
- Nodes: The basic building blocks of the DOM. These can be element nodes, attribute nodes, text nodes, etc.
- Elements: Represent HTML tags like
<div>
,<p>
,<a>
. - Attributes: Properties of HTML elements, like
id
,class
,src
. - Text Nodes: Represent the text content within an element.
Common DOM Manipulation Methods
JavaScript provides a rich set of methods to interact with the DOM. Here are some of the most frequently used:
Selecting Elements
document.getElementById(id)
: Selects an element by its unique ID.document.getElementsByClassName(className)
: Selects all elements with a given class name. Returns an HTMLCollection.document.getElementsByTagName(tagName)
: Selects all elements with a given tag name. Returns an HTMLCollection.document.querySelector(selector)
: Selects the first element that matches a CSS selector.document.querySelectorAll(selector)
: Selects all elements that match a CSS selector. Returns a NodeList.
Creating and Appending Elements
document.createElement(tagName)
: Creates a new element node.parentNode.appendChild(childNode)
: Appends a node as the last child of a parent node.parentNode.insertBefore(newNode, referenceNode)
: Inserts a node before a reference node.
Modifying Element Content and Attributes
element.innerHTML
: Gets or sets the HTML content of an element.element.textContent
: Gets or sets the text content of an element (ignores HTML tags).element.setAttribute(name, value)
: Sets an attribute on an element.element.getAttribute(name)
: Gets the value of an attribute.element.style.property = value
: Modifies inline styles.
Removing Elements
element.remove()
: Removes the element from the DOM.parentNode.removeChild(childNode)
: Removes a child node from its parent.
Live Example: Modifying Text
This text will change!
Live Example: Adding an Element
- Item 1
- Item 2
Best Practices
When performing DOM manipulations, consider the following:
- Performance: Minimize DOM manipulations, especially in loops. Batch changes where possible.
- Readability: Use descriptive variable names and clear logic.
- Event Handling: Use event delegation for efficiency when dealing with many similar elements.
- Frameworks: For complex applications, consider using JavaScript frameworks (like React, Vue, Angular) which provide more structured approaches to DOM management.