This page shows you how to locate and access HTML elements within an HTML page.
In JavaScript, you often need to manipulate HTML elements, and to do so, you must first locate them. There are several methods for finding HTML elements:
The simplest way to locate an HTML element in the DOM is by using its element id.
This example finds the element with id=”intro”:
const element = document.getElementById(“intro”); |
If the element is found, the method will return the element as an object (assigned to element).
If the element is not found, element will be set to null.
This example locates all <p> elements:
const element = document.getElementsByTagName(“p”); |
This example locates the element with id=”main”, and then retrieves all <p> elements within it.
const x = document.getElementById(“main”); const y = x.getElementsByTagName(“p”); |
To find all HTML elements with the same class name, use getElementsByClassName().
This example returns a list of all elements with class=”intro”.
const x = document.getElementsByClassName(“intro”); |
To find all HTML elements that match a specific CSS selector (such as id, class names, types, attributes, or attribute values), use the querySelectorAll() method.
This example returns a list of all <p> elements with class=”intro”.
const x = document.querySelectorAll(“p.intro”); |
This example locates the form element with id=”frm1″ in the forms collection and displays the values of all its elements.
const x = document.forms[“frm1”]; let text = “”; for (let i = 0; i < x.length; i++) { text += x.elements[i].value + “<br>”; } document.getElementById(“demo”).innerHTML = text; |
The following HTML objects (and object collections) are also accessible: