DOM Document
JavaScript HTML DOM Document
Section titled “JavaScript HTML DOM Document”The HTML DOM (Document Object Model) represents an HTML or XML document as a tree-structure of objects. The document object is the entry point to this structure, representing the entire web page.
The HTML DOM document Object
Section titled “The HTML DOM document Object”In the HTML DOM, the document object is the root of the document tree and represents your web page.
It’s the owner of all other nodes (elements, text, comments, etc.) in the page. To access or manipulate any part of an HTML page with JavaScript, you typically start by interacting with the document object.
Below are common ways to use the document object to find and manipulate HTML elements.
Finding HTML Elements
Section titled “Finding HTML Elements”Modern JavaScript provides several powerful methods for selecting HTML elements:
| Method | Description |
|---|---|
document.getElementById(id) | Finds an element by its unique id attribute. Returns a single element object or null. |
document.querySelector(cssSelector) | Finds the first element that matches the specified CSS selector(s). Returns a single element object or null. |
document.querySelectorAll(cssSelector) | Finds all elements that match the specified CSS selector(s). Returns a static NodeList (array-like collection). |
document.getElementsByTagName(tagName) | Finds all elements with the given tag name. Returns a live HTMLCollection. |
document.getElementsByClassName(className) | Finds all elements with the given class name. Returns a live HTMLCollection. |
querySelector and querySelectorAll are often preferred for their flexibility with CSS selectors.
Changing HTML Elements
Section titled “Changing HTML Elements”Once an element is selected, you can modify its content, attributes, and style:
| Property/Method | Description |
|---|---|
element.innerHTML = newHtmlContent | Changes the HTML content (markup) within an element. Use with caution if newHtmlContent comes from untrusted sources due to XSS risks. |
element.textContent = newTextContent | Changes the text content of an element and its descendants. Safer for setting plain text as it automatically escapes HTML. |
element.setAttribute(attributeName, value) | Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added. |
element.style.property = value | Changes an inline CSS style property (e.g., element.style.color = "red"). For more complex styling, managing CSS classes is preferred. |
element.classList.add('className') | Adds a CSS class to the element. |
element.classList.remove('className') | Removes a CSS class from the element. |
element.classList.toggle('className') | Toggles a CSS class on the element. |
Adding and Deleting Elements
Section titled “Adding and Deleting Elements”You can dynamically create, add, and remove HTML elements:
| Method | Description |
|---|---|
document.createElement(tagName) | Creates a new HTML element of the specified tag type. |
parentElement.appendChild(childElement) | Adds childElement as the last child of parentElement. |
parentElement.insertBefore(newElement, referenceElement) | Inserts newElement into parentElement before referenceElement. |
element.append(...nodesOrDOMStrings) | Modern method to insert nodes or DOMStrings after the last child of element. |
element.prepend(...nodesOrDOMStrings) | Modern method to insert nodes or DOMStrings before the first child of element. |
element.before(...nodesOrDOMStrings) | Modern method to insert nodes or DOMStrings before element itself (as a sibling). |
element.after(...nodesOrDOMStrings) | Modern method to insert nodes or DOMStrings after element itself (as a sibling). |
parentElement.removeChild(childElement) | Removes childElement from parentElement. |
element.remove() | Modern method to remove element itself from the DOM. |
parentElement.replaceChild(newChild, oldChild) | Replaces oldChild with newChild within parentElement. |
document.write(text) | Writes directly to the HTML output stream. Strongly discouraged after the document has finished loading as it can overwrite the entire page. Generally avoid. |
Adding Event Handlers
Section titled “Adding Event Handlers”The recommended way to respond to user interactions (like clicks, mouse movements, key presses) is using addEventListener:
| Method | Description |
|---|---|
element.addEventListener(eventType, function, useCapture) | Attaches an event handler function to an element for a specified event type (e.g., ‘click’, ‘mouseover’). useCapture is an optional boolean (default false). |
element.removeEventListener(eventType, function, useCapture) | Removes an event handler previously attached with addEventListener. |
Example: document.getElementById('myButton').addEventListener('click', function() { alert('Button clicked!'); });
While older methods like element.onclick = function(){...} exist, addEventListener is preferred because it allows multiple handlers for the same event, offers more control over the event propagation phase (capturing/bubbling), and is more aligned with modern event handling patterns.
Common document Properties
Section titled “Common document Properties”The document object has many properties providing information about the document:
| Property | Description |
|---|---|
document.body | Returns the <body> element of the current document. |
document.head | Returns the <head> element of the current document. |
document.documentElement | Returns the root element of the document (usually the <html> element). |
document.title | Gets or sets the title of the document (text within the <title> tag). |
document.URL | Returns the complete URL of the document. |
document.cookie | Gets or sets the cookies associated with the document. For modern applications, consider Web Storage (localStorage, sessionStorage) or more robust cookie management techniques. |
document.forms | Returns an HTMLCollection of all <form> elements in the document. |
document.images | Returns an HTMLCollection of all <img> elements in the document. |
document.links | Returns an HTMLCollection of all <a> (with href) and <area> elements. |
document.scripts | Returns an HTMLCollection of all <script> elements. |
document.readyState | Returns the (loading) status of the document (e.g., ‘loading’, ‘interactive’, ‘complete’). |
document.characterSet | Returns the character set (encoding) being used by the document. |
document.doctype | Returns the Document Type Definition (DTD) of the current document. |
Properties like document.applets are deprecated and should not be used. The DOM specification is a living standard, so always refer to current MDN documentation for the latest information.