DOM Methods
JavaScript - Interacting with the HTML DOM
Section titled “JavaScript - Interacting with the HTML DOM”The HTML DOM (Document Object Model) provides a programming interface for HTML documents. It represents the page structure as a tree of objects, allowing JavaScript to dynamically access and modify the content, structure, and style of a web page.
DOM properties are values of HTML elements that you can get or set (e.g., element.textContent).
DOM methods are actions you can perform on HTML elements (e.g., element.appendChild()).
The DOM Programming Interface
Section titled “The DOM Programming Interface”When an HTML document is loaded in a browser, it becomes a document object. This object is the entry point to the content of the page (the DOM tree). All HTML elements are defined as objects with their own properties and methods.
Common tasks include:
- Finding HTML elements.
- Changing HTML content and attributes.
- Changing CSS styles.
- Adding or deleting HTML elements.
- Responding to user events.
Finding HTML Elements
Section titled “Finding HTML Elements”To manipulate an HTML element, you first need to find it. JavaScript offers several methods:
1. document.getElementById(id)
Section titled “1. document.getElementById(id)”This is a classic and efficient way to find a single element by its unique id attribute.
const mainTitle = document.getElementById("main-title");if (mainTitle) { mainTitle.style.color = "blue";}2. document.querySelector(cssSelector)
Section titled “2. document.querySelector(cssSelector)”A powerful and versatile modern method that returns the first element within the document that matches the specified CSS selector(s).
// Find the first <p> elementconst firstParagraph = document.querySelector("p");
// Find the element with id "contact-form"const contactForm = document.querySelector("#contact-form");
// Find the first element with class "highlight"const highlightedItem = document.querySelector(".highlight");
// Find a <button> inside a <form> with id "login-form"const loginButton = document.querySelector("form#login-form button.submit-btn");3. document.querySelectorAll(cssSelector)
Section titled “3. document.querySelectorAll(cssSelector)”Returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors. You can then iterate over this list.
const listItems = document.querySelectorAll("ul.product-list li");listItems.forEach(item => { item.style.fontWeight = "bold";});Other older methods (less commonly used directly now, but good to know):
document.getElementsByTagName(tagName): Returns a liveHTMLCollectionof elements with the given tag name.document.getElementsByClassName(className): Returns a liveHTMLCollectionof elements with the given class name.
querySelector and querySelectorAll are generally preferred for their flexibility with CSS selectors.
Changing HTML Content
Section titled “Changing HTML Content”Once you have a reference to an element, you can change its content:
1. element.textContent
Section titled “1. element.textContent”Gets or sets the text content of an element and its descendants. This is generally the safest and often most performant way to deal with text. It treats the content as plain text, not HTML.
const messageDiv = document.getElementById("message");if (messageDiv) { messageDiv.textContent = "Welcome, User!"; // Safely sets text}2. element.innerHTML
Section titled “2. element.innerHTML”Gets or sets the HTML markup contained within an element. Use this when you need to insert HTML structure. Be cautious: setting innerHTML with content from untrusted sources can lead to Cross-Site Scripting (XSS) vulnerabilities because it parses and executes the HTML, including any <script> tags.
const productInfo = document.getElementById("product-details");if (productInfo) { productInfo.innerHTML = "**Product Name:** Awesome Gadget <br> <em>Limited stock!</em>";}Security Note: Always sanitize or carefully validate any user-provided data before inserting it into the DOM using innerHTML. Prefer textContent when dealing with plain text to avoid XSS risks. |
|---|
Modifying Element Attributes
Section titled “Modifying Element Attributes”You can change HTML attributes directly as properties on the element object (for common attributes) or using setAttribute and getAttribute.
const myImage = document.getElementById("banner-image");if (myImage) { myImage.src = "new-image.jpg"; // Directly setting 'src' property myImage.alt = "A new beautiful banner image";
// Using methods myImage.setAttribute("data-custom-info", "extra details"); console.log(myImage.getAttribute("data-custom-info"));
myImage.removeAttribute("title");}Creating and Adding Elements
Section titled “Creating and Adding Elements”You can dynamically create new HTML elements and add them to the DOM.
const list = document.getElementById("my-list");if (list) { // Create a new <li> element const newItem = document.createElement("li");
// Set its content newItem.textContent = "New item added dynamically!";
// Add a class for styling newItem.classList.add("list-item-dynamic");
// Append the new <li> to the <ul> list.appendChild(newItem);}
// Other methods for adding elements include:// parentNode.insertBefore(newNode, referenceNode)// element.prepend(...nodes)// element.append(...nodes)// element.replaceWith(...nodes)Learning these DOM manipulation methods allows for rich, dynamic web applications where content can change without reloading the entire page.