Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML DOM Access

HTML DOM Access


Access the HTML DOM - find HTML elements.


Access HTML Elements (Nodes)

Accessing an HTML element is the same as accessing a node

You can access HTML elements in different ways:


The 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 »


The getElementsByTagName() method

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

Syntax

node

.getElementsByTagName(

"tagname"

);

The following example returns a list containing all

elements in the document:

Example 1

document

.

getElementsByTagName

(

"

p

"

)

;

Try it »

The following example returns a list containing all

elements in the list, and these

elements should be descendants (children, grandchildren, and so on) of the element with id="main":

Example 2

document

.

getElementById

(

"

main

"

)

.

getElementsByTagName

(

"

p

"

)

;

Try it »


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 containing all elements with class="intro":

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