Accessing HTML DOM
Accessing HTML DOM - Finding HTML Elements.
Accessing HTML Elements (Nodes)
Accessing HTML elements is equivalent to accessing nodes.
You can access HTML elements in different ways:
- By using the getElementById() method
- By using the getElementsByTagName() method
- By using the getElementsByClassName() method
The getElementById() Method
The getElementById() method returns a reference to the element with the specified ID:
Syntax
The following example retrieves the element with id="intro":
Example
document.getElementById("intro");
The getElementsByTagName() Method
The getElementsByTagName() method returns all elements with the specified tag name.
Syntax
The following example returns a list of all <p> elements in the document:
Example 1
document.getElementsByTagName("p");
The following example returns a list of all <p> elements that are descendants (children, grandchildren, etc.) of the element with id="main":
Example 2
document.getElementById("main").getElementsByTagName("p");
The getElementsByClassName() Method
Use this method if you want to find all HTML elements with the same class name:
The example above returns a list of all elements with class="intro".
Note: getElementsByClassName() does not work in Internet Explorer 5, 6, 7, 8.