Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  95] [ 7]  / answers: 1 / hits: 17310  / 15 Years ago, tue, may 19, 2009, 12:00:00

I am traversing a HTML document using javascript DOM. I want make a list (an array actually) of all nodes/elements and their values. 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 something.



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?


More From » dom

 Answers
6

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.length; i++ )
traverseAndStore( node.childNodes[i] );
}

[#99505] Thursday, May 14, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;