JavaScript: iterating over DOM nodes

JavaScript implements the DOM like many other languages. The DOM is a model that represents a hierarchy of page elements, called nodes. In the HTML implementation, nodes can be grouped by node collections. These collections are a live representation of the page structure. In this post I'm going to show you how to iterate over DOM nodes first by getting an HTML node collection using getElementsByTagName() and then with a normal for loop. Let's say that we have a page like this:

<ul id="test">



<form id="test-form" action="" method="get">

    <div><input type="text" name="q" id="q" />
    <input type="submit" value="Test" id="subtest" name="subtest" />


We want to retrieve all the list items and the input fields. Here's how:

var Iterator = {

    iterate: function(values) {
       var i, len = values.length, html = '';
       var htmlBody = document.getElementsByTagName('body')[0].innerHTML;
       for(i = 0; i<len; i += 1) {
          html += '<div>' + (i+1) + ': ' + values[i].tagName.toLowerCase() + '</div>';
       return document.body.innerHTML = htmlBody + html;


function List(reference) {

    this.reference = document.getElementById(reference);
    this.items = this.reference.getElementsByTagName('li');


function Form(hook) {

    this.hook = document.getElementById(hook);
    this.inputs = this.hook.getElementsByTagName('input');


var list = new List('test');
var form = new Form('test-form');


The Iterator object has a method called iterate() that performs a loop through all the values passed in as its sole argument. These values are actually two NodeLists obtained from the List and Form objects using getElementsByTagName().


Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.