问题描述
什么是唯一标识HTML文档中所有DOM节点的方法。为了说明我的意思,这里是一个(虚构的)示例:
What is a way to uniquely identify all DOM nodes in an HTML document. To illustrate what I mean, here is a (fictional) example:
- 脚本X从document.html随机选择一个DOM节点。 li>
- 脚本X需要告诉脚本Y它选择了哪个DOM节点。
- 脚本X如何唯一标识所选择的DOM节点,以便脚本Y知道document.html中的哪个节点?
我真的很感兴趣如何唯一标识DOM节点,以便脚本Y可以识别并操纵它。优选地,它也应该与文本节点一起工作。我正在考虑XPath,但我不知道如何为任何给定的节点生成一个独特的 XPath。
I'm really interested in how to uniquely identify the DOM node so that the script Y can identify it and manipulate it. Preferably, it should work with text nodes as well. I was thinking of XPath maybe, but I'm not sure how to generate a unique XPath to any given node.
推荐答案
您应该能够通过从节点向根节点向后工作来确定一个唯一的XPath,并跟踪您所在的节点,以及哪些兄弟节点,以便获得以下内容: p>
You should be able to determine a unique XPath by working backwards from the node to the root node, and tracking the node you're on, and which sibling it is, such that you get something like:
/a[1]/b[2]/c[101]/text()
所以这是第二个 B下的第101个
C
/ code>节点等。因此,这是一个唯一的路径,可以参考原始文档复制
so that's the 101st
C
node under the second B
node, etc. As such, that's a unique path and can be copied around with reference to the original document
这篇关于唯一标识DOM节点的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!