JavaScript HTML DOM Element
- Previous Page DOM Documentation
- Next Page DOM HTML
This chapter explains how to find and access HTML elements in an HTML page.
Finding HTML elements
Generally, through JavaScript, you need to manipulate HTML elements.
To achieve this, you need to first find these elements. There are several ways to complete this task:
- Finding HTML elements by id
- Finding HTML elements by tag name
- Finding HTML elements by class name
- Finding HTML elements through CSS selectors
- Finding HTML elements through HTML object collections
Finding HTML elements by id
The simplest way to find HTML elements in the DOM is to use the element's id.
This example finds the element with id="intro":
Example
var myElement = document.getElementById("intro");
If the element is found, this method will return the element as an object (in myElement).
If the element is not found, myElement will contain null
.
Finding HTML elements by tag name
This example finds all <p>
Element:
Example
var x = document.getElementsByTagName("p");
This example finds the element with id="main" and then finds all elements within "main" <p>
Element:
Example
var x = document.getElementById("main"); var y = x.getElementsByTagName("p");
Finding HTML elements by class name
If you need to find all HTML elements with the same class name, please use getElementsByClassName()
.
This example returns a list of all elements containing class="intro":
Example
var x = document.getElementsByClassName("intro");
Finding elements by class name is not applicable to Internet Explorer 8 and earlier versions.
Finding HTML elements through CSS selectors
If you need to find all HTML elements that match the specified CSS selector (id, class name, type, attribute, attribute value, etc.), please use querySelectorAll()
Method.
This example returns all elements with class="intro" <p>
Element list:
Example
var x = document.querySelectorAll("p.intro");
querySelectorAll()
Not applicable to Internet Explorer 8 and earlier versions.
Find HTML objects through HTML object selectors
This example finds the form element with id="frm1" in the forms collection, and then displays all element values:
Example
var x = document.forms["frm1"]; var text = ""; var i; for (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:
- Previous Page DOM Documentation
- Next Page DOM HTML