Ad

Ad

Sunday, 4 May 2014

JavaScript HTML DOM Nodelist

A nodelist is an array of nodes (like an array of all HTML elements)

HTML DOM Node List

The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code selects all <p> nodes in a document:

Example

var x=document.getElementsByTagName("p");
The nodes can be accessed by index number. To access the second <p> you can write:
y=x[1];

Try it Yourself »
Note: The index starts at 0.

HTML DOM Node List Length

The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:

Example

x=document.getElementsByTagName("p");

for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}

Try it Yourself »
Example explained:
  1. Get all <p> element nodes
  2. For each <p> element, output the value of its text node

No comments:

Post a Comment