HTML DOM Access


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

getElementById() Method

The getElementById() method returns a reference to the element with the specified ID:

Syntax

node.getElementById("id");

The following example gets the element with id="intro":

Example

document.getElementById("intro");

Try it Yourself »


getElementsByTagName() Method

getElementsByTagName() returns all elements with the specified tag name.

Syntax

node.getElementsByTagName("tagname");

The following example returns a list of all <p> elements in the document:

Example 1

document.getElementsByTagName("p");

Try it Yourself »

The following example returns a list of all <p> elements in the document, and these <p> elements should be descendants (children, grandchildren, etc.) of the element with id="main":

Example 2

document.getElementById("main").getElementsByTagName("p");

Try it Yourself »


The getElementsByClassName() Method

If you want to find all HTML elements with the same class name, use this method:

document.getElementsByClassName("intro");

The above example returns a list of all elements with class="intro":

Note:getElementsByClassName() does not work in Internet Explorer 5, 6, 7, 8.

Other Extensions