HTML DOM access



Access HTML DOM - Find 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

getElementById() method returns the element with the specified ID:

Syntax

node.getElementById("id");

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

Instance

<html><!DOCTYPE html>
<html>
<body>

<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>

<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


getElementsByTagName() method

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

Syntax

node.getElementsByTagName("tagname");

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

Instance

<html><!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<script>
x=document.getElementsByTagName("p");
document.write("Text of first paragraph: " + x[0].innerHTML);
</script>

</body>
</html>

Run Example»

Click "Run" Example" button to view online examples

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

Instance

<html><!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>

<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>

<script>
x=document.getElementById("main").getElementsByTagName("p");
document.write("First paragraph inside the div: " + x[0].innerHTML);
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view online Example


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

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