Search w3schools.com:

SHARE THIS PAGE

HTML DOM Access


Accessing the HTML DOM - Finding HTML elements


Accessing HTML Elements (Nodes)

Accessing an HTML element is the same as accessing a Node.

You can access an HTML element 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 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 »


The getElementsByTagName() Method

getElementsByTagName() returns all elements with a 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 that are descendants (children, grand-children, 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 example above returns a list of all elements with class="intro".

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



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]