ES6 - HTML DOM
ES6+ and The HTML Document Object Model (DOM)
Section titled “ES6+ and The HTML Document Object Model (DOM)”Every web page loaded in a browser has a corresponding Document Object Model (DOM). The DOM represents the HTML document as a tree-like structure of objects, where each object corresponds to a part of the document (like elements, attributes, and text). JavaScript can interact with the DOM to access, modify, create, or delete elements and content, making web pages dynamic and interactive.
The DOM is a language-neutral API (Application Programming Interface) standardized by the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG). Modern browsers implement this standard DOM, providing a consistent way to manipulate web documents.
DOM Hierarchy (Conceptual)
Section titled “DOM Hierarchy (Conceptual)”The DOM organizes objects in a hierarchy. At the top is the window object, representing the browser window. The window object has a document property, which is the entry point to the page’s content.
Window: The global object in client-side JavaScript, representing the browser window or tab.Document: Represents the entire HTML document loaded in the window. It’s the root of the document tree.-
**`Element`**: Represents an HTML element (e.g., `<p>`, `<div>`, `<img>`). Elements can contain other elements, text, or attributes.
-
**`Attribute`**: Represents an attribute of an element (e.g., `id`, `class`, `src`).
-
**`TextNode`**: Represents the textual content within an element.
This tree structure allows scripts to navigate and manipulate the document by accessing these objects and their properties and methods.
Accessing DOM Elements
Section titled “Accessing DOM Elements”JavaScript provides several methods to select elements from the DOM:
document.getElementById(id): Returns the element with the specifiedid. Since IDs should be unique, this returns a single element ornull.document.getElementsByTagName(tagName): Returns an HTMLCollection (live, array-like object) of elements with the specified tag name.document.getElementsByClassName(className): Returns an HTMLCollection of elements that have the specified class name.document.querySelector(cssSelector): Returns the first element within the document that matches the specified CSS selector(s). If no matches are found,nullis returned.document.querySelectorAll(cssSelector): Returns a static NodeList (array-like object) representing a list of the document’s elements that match the specified group of CSS selectors.
querySelector and querySelectorAll are generally preferred for their flexibility as they use CSS selectors, which are powerful and familiar to web developers.
Example: Accessing Elements
Section titled “Example: Accessing Elements”<!DOCTYPE html><html><head><title>DOM Access</title></head><body> <h1 id="main-title">Welcome</h1> <p class="content">This is a paragraph.</p> <p class="content">Another paragraph.</p> <div><button>Click Me</button></div>
<script> const titleElement = document.getElementById('main-title'); console.log('Title Element:', titleElement.textContent); // Welcome
const paragraphs = document.getElementsByClassName('content'); console.log('Number of paragraphs:', paragraphs.length); // 2 for (let i = 0; i < paragraphs.length; i++) { console.log(`Paragraph ${i+1}:`, paragraphs[i].textContent); }
const firstButton = document.querySelector('div button'); console.log('First button text:', firstButton.textContent); // Click Me
const allParagraphsQuery = document.querySelectorAll('p.content'); allParagraphsQuery.forEach(p => console.log('QuerySelectorAll P:', p.textContent)); </script></body></html>Modifying DOM Elements
Section titled “Modifying DOM Elements”Once you have a reference to an element, you can modify its content, attributes, and style.
- Content:
element.textContent: Gets or sets the text content of an element and its descendants (plain text).element.innerHTML: Gets or sets the HTML content (markup) within an element. Use with caution due to potential security risks (XSS) if setting with untrusted user input.- Attributes:
element.getAttribute(name): Gets the value of an attribute.element.setAttribute(name, value): Sets the value of an attribute.element.removeAttribute(name): Removes an attribute.element.id,element.className, etc.: Direct property access for common attributes.element.classList: An object to manipulate classes (add,remove,toggle,contains).- Style:
element.style.propertyName: Gets or sets inline CSS styles (e.g.,element.style.color = 'blue';). Property names are camelCased (e.g.,backgroundColor).
Example: Modifying Elements
Section titled “Example: Modifying Elements”<!DOCTYPE html><html><head><title>DOM Modification</title></head><body> <p id="myParagraph">Initial text.</p> <img id="myImage" src="old-image.jpg" alt="An image">
<script> const p = document.getElementById('myParagraph'); p.textContent = 'Text updated by JavaScript!'; p.style.color = 'green'; p.style.fontWeight = 'bold';
const img = document.getElementById('myImage'); img.setAttribute('src', 'new-image.png'); img.alt = 'A new image provided by script'; // Direct property access
p.classList.add('highlight'); // Assuming CSS: .highlight { background-color: yellow; } </script></body></html>Creating and Appending/Removing Elements
Section titled “Creating and Appending/Removing Elements”You can also create new HTML elements and add them to the DOM, or remove existing ones.
document.createElement(tagName): Creates a new element.document.createTextNode(text): Creates a new text node.parentElement.appendChild(childElement): AddschildElementas the last child ofparentElement.parentElement.insertBefore(newNode, referenceNode): InsertsnewNodebeforereferenceNodewithinparentElement.element.remove(): Removes the element from the DOM (modern method).parentElement.removeChild(childElement): RemoveschildElementfromparentElement(older method).
Example: Creating and Adding Elements
Section titled “Example: Creating and Adding Elements”<!DOCTYPE html><html><head><title>DOM Creation</title></head><body> <div id="container"></div>
<script> const container = document.getElementById('container');
// Create a new <h2> element const newHeading = document.createElement('h2'); newHeading.textContent = 'Dynamically Added Heading';
// Create a new <p> element const newParagraph = document.createElement('p'); newParagraph.textContent = 'This paragraph was created and added using JavaScript.';
// Append the new elements to the container container.appendChild(newHeading); container.appendChild(newParagraph);
// To remove the heading after 2 seconds (example) setTimeout(() => { if (document.body.contains(newHeading)) { // Check if still in DOM newHeading.remove(); } }, 2000); </script></body></html>Note on Legacy DOM features:
Section titled “Note on Legacy DOM features:”Older tutorials might mention properties like document.alinkColor, document.bgColor, or methods like document.write() for DOM manipulation during page load, or document.clear(). Most of these are deprecated or considered bad practice in modern web development. For styling, use CSS. For dynamic content updates after the page has loaded, use the DOM manipulation methods described above (textContent, appendChild, etc.) instead of document.write().
Understanding the DOM and how to manipulate it is fundamental for creating interactive and dynamic web applications. Always refer to up-to-date resources like MDN Web Docs for the latest information on DOM APIs.