Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the unique identifier for a DOM element/node

Tags:

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?

like image 484
Annibigi Avatar asked May 19 '09 09:05

Annibigi


People also ask

Do DOM elements have unique ids?

OK, there is no ID associated to DOM element automatically. DOM has a hierarchycal structure of elements which is the main information. From this perspective, you can associate data to DOM elements with jQuery or jQLite. It can solve some issues when you have to bind custom data to elements.

How do I identify a DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.

What is a DOM element node?

domnodeelement. 10 Comments. The Document Object Model (DOM) is an interface that treats HTML or XML document as a tree structure, where each node is an object of the document. DOM also provides a set of methods to query the tree, alter the structure, style.

What is DOM node type?

The nodeType property returns the node type, as a number, of the specified node. If the node is an element node, the nodeType property will return 1. If the node is an attribute node, the nodeType property will return 2. If the node is a text node, the nodeType property will return 3.


1 Answers

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] ); } 
like image 52
jrharshath Avatar answered Sep 22 '22 17:09

jrharshath