JavaScript HTML DOM Elements
This page explains how to find and access HTML elements using JavaScript.
Finding HTML Elements
When using JavaScript to manipulate HTML elements, you need to find the elements first. Here are several methods to do this:
- Finding HTML Elements by ID
- Finding HTML Elements by Tag Name
- Finding HTML Elements by Class Name
- Finding HTML Elements by CSS Selectors
- Finding HTML Elements by HTML Object Collections
Finding HTML Elements by ID
The simplest way to find an HTML element in the DOM is by using the element's ID.
Example:
If the element is found, the method returns the element as an object. If not, element will be null.
Finding HTML Elements by Tag Name
To find all elements with a specific tag name:
Example:
const elements = document.getElementsByTagName("p");
To find all <p> elements inside an element with id="main":
Example:
const mainElement = document.getElementById("main");
const paragraphs = mainElement.getElementsByTagName("p");
Finding HTML Elements by Class Name
To find all HTML elements with the same class name, use getElementsByClassName().
Example:
const elements = document.getElementsByClassName("intro");
Finding HTML Elements by CSS Selectors
To find all HTML elements that match a specified CSS selector, use querySelectorAll().
Example:
const elements = document.querySelectorAll("p.intro");
Finding HTML Elements by HTML Object Collections
To find elements using HTML object collections, such as forms, use their properties.
Example:
const form = document.forms["frm1"];
let text = "";for (let i = 0; i < form.length; i++)
{ text += form.elements[i].value +
"<br>";}document.getElementById("demo").innerHTML = text;
The following HTML objects (and object collections) are also accessible:
- document.anchors
- document.body
- document.documentElement
- document.embeds
- document.forms
- document.head
- document.images
- document.links
- document.scripts
- document.title
Test Yourself With Exercises
Exercise:
Use the getElementById method to find the <p> element and change its text to "Hello".
Example:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello";
</script>