tags:

views:

85

answers:

3

What is a way to uniquely identify all DOM nodes in an HTML document. To illustrate what I mean, here is a (fictional) example:

  • Script X randomly selects a DOM node from document.html.
  • Script X needs to tell script Y which DOM node it has chosen.
  • How does script X uniquely identify the DOM node it has chosen so that script Y knows exactly which node it is in document.html?

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.

A: 

Well, an XPath expression that results in a single node should be unique. What do you mean by "how to generate a unique XPath to any given node"?

Right but I'm doing it in reverse: I know which node I'm at but not how to get there ;) Brian's answer seems good enough though.
Olivier Lalonde
+3  A: 

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()

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

Brian Agnew
What if there is a script Z that manipulates the DOM too?
Till Backhaus
Xpath implementations are available in most languages. On the command line you can use a command-line tool called xmlstarlet (just Google for it)
Brian Agnew
Exactly what I was looking for! What if my code looked like this:<div><p>hello <b>dear</b> world</p></div>. How could I identify the " world" node. Would I do something like this? /div[0]/p[0]/text[1] ?
Olivier Lalonde
Yes. But Xpath is 1-based, not 0-based
Brian Agnew
Oops, thanks for pointing out.
Olivier Lalonde
A: 

Ordinal child positions along XPath axes. Nodes are strongly ordered, and so saying:

child 1 of child 3 of child 4 of child 5.

should do it.

bmargulies