[ACCEPTED]-What is the unique identifier for a DOM element/node-dom

Accepted answer
Score: 27

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

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

In javascript, all objects are passed around 2 by reference. So here's a sample code for 1 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] );
}
Score: 1

You can get something similar to xpath with 4 something like this. It traverses the dom 3 upwards from the input element through the 2 parentNode property.

https://gist.github.com/sebjwallace/3c0a6f7493ce23134516

It will output a string 1 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;
}

More Related questions