Skip to content

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()).

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.

To manipulate an HTML element, you first need to find it. JavaScript offers several methods:

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";
}

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> element
const 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");

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 live HTMLCollection of elements with the given tag name.
  • document.getElementsByClassName(className): Returns a live HTMLCollection of elements with the given class name.

querySelector and querySelectorAll are generally preferred for their flexibility with CSS selectors.

Once you have a reference to an element, you can change its content:

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
}

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.

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");
}

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.