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, bu
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] );
}
You can get something similar to xpath with something like this. It traverses the dom upwards from the input element through the parentNode property.
https://gist.github.com/sebjwallace/3c0a6f7493ce23134516
It will output a string like this.
"#document/HTML/BODY/DIV"
var getElementPath = function(el){
var path = el.nodeName;
var parent = el.parentNode;
while(parent){
path = parent.nodeName + '/' + path;
parent = parent.parentNode;
}
return path;
}