DOM Elements
JavaScript and HTML DOM Elements
Section titled “JavaScript and HTML DOM Elements”This chapter explains how to find and access HTML elements within an HTML document using JavaScript. This is fundamental for dynamic web page manipulation.
Finding HTML Elements
Section titled “Finding HTML Elements”To manipulate HTML elements with JavaScript (e.g., change their content, style, or attributes), you first need to find and get a reference to them. The Document Object Model (DOM) provides several methods for this:
- Finding HTML element by its unique ID (
getElementById) - Finding HTML elements by tag name (
getElementsByTagName) - Finding HTML elements by class name (
getElementsByClassName) - Finding HTML elements using CSS selectors (
querySelector,querySelectorAll) - Accessing elements through HTML object collections (e.g.,
document.forms,document.images)
Finding HTML Element by ID
Section titled “Finding HTML Element by ID”The most common and efficient way to find a single, specific HTML element is by its id attribute, which should be unique within the document.
The document.getElementById('elementId') method returns the element object if found, or null if no element with that ID exists.
// Assuming HTML: <div id="intro">Hello World</div>const introElement = document.getElementById("intro");
if (introElement) { // introElement is now a reference to the <div> object console.log(introElement.textContent); // Outputs: "Hello World"} else { console.log("Element with ID 'intro' not found.");}Finding HTML Elements by Tag Name
Section titled “Finding HTML Elements by Tag Name”document.getElementsByTagName('tagName') returns a live HTMLCollection of all elements with the specified tag name (e.g., ‘p’, ‘div’, ‘img’).
An HTMLCollection is an array-like object. It’s ‘live’, meaning it automatically updates if elements are added or removed from the DOM that match the selector.
// Assuming HTML has multiple <p> elementsconst paragraphs = document.getElementsByTagName("p");console.log(`Found ${paragraphs.length} paragraph elements.`);
// You can iterate through an HTMLCollection using a for loop:for (let i = 0; i < paragraphs.length; i++) { // paragraphs[i].style.color = "blue"; // Example: Change text color}
// To use array methods like forEach, convert it to an array:// Array.from(paragraphs).forEach(p => console.log(p.textContent));You can also call getElementsByTagName on an element to find descendants of that element:
// Assuming HTML: <div id="main"><p>First</p><p>Second</p></div>const mainDiv = document.getElementById("main");if (mainDiv) { const paragraphsInMain = mainDiv.getElementsByTagName("p"); console.log(`Found ${paragraphsInMain.length} paragraphs inside 'main' div.`); // Outputs: 2}Finding HTML Elements by Class Name
Section titled “Finding HTML Elements by Class Name”document.getElementsByClassName('className') returns a live HTMLCollection of all elements that have the specified class name.
An element can have multiple classes; this method finds elements if the specified class is one of them.
// Assuming HTML: <p class="info">Msg1</p> <div class="info warning">Msg2</div>const infoElements = document.getElementsByClassName("info");console.log(`Found ${infoElements.length} elements with class 'info'.`); // Outputs: 2
// Similar to HTMLCollection from getElementsByTagName, iterate with a for loop or convert to array.for (let i = 0; i < infoElements.length; i++) { // infoElements[i].style.fontWeight = "bold";}Finding HTML Elements by CSS Selectors
Section titled “Finding HTML Elements by CSS Selectors”Modern JavaScript provides powerful methods that use CSS selectors to find elements:
document.querySelector('cssSelector'): Returns the first element in the document that matches the specified CSS selector. If no match is found, it returnsnull.document.querySelectorAll('cssSelector'): Returns a static (not live)NodeListcontaining all elements in the document that match the specified CSS selector(s). If no matches are found, it returns an emptyNodeList.
CSS selectors can be simple (e.g., 'p.intro') or complex (e.g., 'div#main > ul li:nth-child(odd)').
// Example using querySelector (finds the first match)// HTML: <p class="highlight">First highlight</p><p class="highlight">Second highlight</p>const firstHighlight = document.querySelector(".highlight");if (firstHighlight) { // firstHighlight.style.backgroundColor = "yellow";}
// Example using querySelectorAll (finds all matches)const allParagraphsWithIntroClass = document.querySelectorAll("p.intro");console.log(`Found ${allParagraphsWithIntroClass.length} <p> elements with class 'intro'.`);
// NodeList can be iterated with forEach directly:allParagraphsWithIntroClass.forEach(function(element) { // console.log(element.textContent);});
// Or using a for...of loop (more modern):for (const element of allParagraphsWithIntroClass) { // console.log(element.textContent);}querySelector and querySelectorAll are very versatile and often preferred for their flexibility and the static nature of NodeList from querySelectorAll (which can be simpler to work with than live collections in some scenarios).
Finding HTML Elements by HTML Object Collections
Section titled “Finding HTML Elements by HTML Object Collections”The DOM also provides direct access to certain collections of HTML elements, like forms, images, links, etc.
These are properties of the document object and usually return an HTMLCollection.
Example: Accessing form elements:
// Assuming HTML: <form id="myForm"><input type="text" name="username"><input type="submit"></form>const myForm = document.forms["myForm"]; // Or document.getElementById('myForm')// const myForm = document.forms[0]; // Access by index if it's the first form
if (myForm) { let text = "Form elements: \n"; // myForm.elements is an HTMLFormControlsCollection for (let i = 0; i < myForm.elements.length; i++) { const element = myForm.elements[i]; text += `Name: ${element.name || 'N/A'}, Type: ${element.type}, Value: ${element.value}\n`; } console.log(text); // To display in HTML (e.g., in a <pre> tag with id="demo"): // document.getElementById("demo").textContent = text.replace(/\n/g, "<br>"); // If displaying as HTML with line breaks}Other accessible HTML object collections include:
document.anchors(all<a>elements with anameattribute - largely legacy)document.body(the<body>element)document.documentElement(the root<html>element)document.embeds(all<embed>elements)document.forms(all<form>elements)document.head(the<head>element)document.images(all<img>elements)document.links(all<a>and<area>elements with anhrefattribute)document.scripts(all<script>elements)document.title(the content of the<title>tag as a string)
While these collections are available, using getElementById, querySelector, or querySelectorAll is often more consistent and powerful for general element selection.
Further reading: MDN: Locating DOM elements