What is the unique identifier for a DOM element/node

后端 未结 2 1154
粉色の甜心
粉色の甜心 2020-12-30 00:47

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

2条回答
  •  长情又很酷
    2020-12-30 01:35

    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

提交回复
热议问题