什么是DOM元素/节点的唯一标识符 [英] What is the unique identifier for a DOM element/node

查看:944
本文介绍了什么是DOM元素/节点的唯一标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript DOM遍历HTML文档。我想要创建所有节点/元素及其值的列表(实际上是一个数组)。我发现了一个用于遍历DOM的脚本,但是如何将每个节点值存储在数组中。我似乎找不到节点的唯一标识符。任何人都有任何指针?我正在考虑 xpath 或某事。



这是一个好主意,考虑 xpath 作为唯一标识符。如果是,如何在遍历DOM时获取元素的 xpath

解决方案

作为C和C ++世界的程序员,我对这种问题的第一个回答就是将它们的地址存储在数组中。但是经过几年的网络交易,我可以给出正确的答案:



在javascript中,您可以直接存储引用到数组中的对象。
没有,xpath不是一个好主意;使用引用更简单和更好。
所以直接回答你的问题是:除了本身之外,DOM元素/节点没有唯一的标识符。



javascript,所有对象都通过引用传递。所以这里是一个如何做的代码:

  var theArray = []; 
var theNodeToTraverse = document.getElementById('domelementtosearch');

traverseAndStore(theNodeToTraverse);

函数遍历和存储(节点)
{
if(node == null)return;
theArray [theArray.length] = node;
for(i = 0; i< node.childNodes.length; i ++)
traverseAndStore(node.childNodes [i]);
}


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?

解决方案

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] );
}

这篇关于什么是DOM元素/节点的唯一标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆