tags:

views:

622

answers:

1

I am traversing a HTML document using javascript DOM. I want make a list (an array actually) of all nodes/elements and thier values. On w3schools website i found a script for traversing DOM but how do i store each node value in an array. I can't seem to find the unique identifier for a node. Anyone has any pointers? I was thinking of xpath or sumthing.

Is it a good idea to consider xpath for node as the unique identifier. If so how do i get xpath of a element while traversing the DOM.

thanks in advance for your help

+4  A: 

As programmer born and brought up in the world of C and C++, my first answer to this kind of question would have been "store their addresses in the array!". But after a couple years of messing around with the web way of things, I can give the right answer:

In javascript, you can directly store the references to the objects in the array. And no, xpath is not a good idea for this; using references is simpler and better. So a direct answer to your question is: there is no unique identifier for a DOM element/node except itself.

In javascript, all objects are passed around by reference. So here's a sample code for how to do it:

var theArray = [];
var theNodeToTraverse = document.getElementById('domelementtosearch');

traverseAndStore(theNodeToTraverse);

function traverseAndStore( node )
{
    if( node==null) return;
    theArray[ theArray.length ] = node;
    for( i=0; i<node.childNodes.lenght; i++ )
        traverseAndStore( node.childNodes[i] );
}

Thats it, folks!

cheers, jrh

Here Be Wolves
hey thnx for your comments!
Annibigi