开发者

How can I find a text node in the live DOM using its copy/clone?

I've copied some text nodes from the page (i.e., live DOM) and have stored them in an array. Is it possible to locate those exact nodes again in the live DOM? I would need to use plain JavaScript.

This is basically how my project works:

  • A configuration object specifies sections of the page (using CSS selectors) where there is some text content, and optionally subsections within that section (also using CSS selectors) where there is text content that should be ignored. The property names that I use, respectively, are select and exclude.
  • Using Sizzle (jQuery's selector engine), I generate an element collection for each of the select selectors, then clone it.
  • I then run the exclude selectors against the select collection, finding any elements that match, and remove them from the select collection.
  • Using the select collection with the removed exclude sections, I traverse it to build an array of only the text nodes.
  • I use this array of text nodes to do some word matching based on a supplied list of terms that may be in the original text content. To do this, I build an array of objects that include properties like the text node in which a term was found, and at what position/offset that term occurs within the text node's data.
  • 开发者_运维技巧

Given the latter array, I need to be able to match the cloned text nodes in which matching terms were found to the original text nodes from which they were cloned. If I can do this, I can just iterate over my array of objects, first finding the text node that corresponds to the live DOM (from which it was originally cloned), and then linking the term at the position/offset that I have recorded in the object.

Hopefully this makes some sense - please let me know if not, and I can provide more details. This must be deterministic - i.e., I can't just search the live DOM for a text node that has the same data, as that may lead to false positives.

Again, I must use plain JavaScript here, not jQuery or any other libraries.

I appreciate any help!


In general, you can't. Once you've cloned, the new clones have a different identity to the old nodes. There is no general-purpose way to tie a node back to the node it was cloned from.

If you know the topmost cloned ancestor node, and the node in the document that it was cloned from, you can naturally use the index of each ancestor in its parent childNode list to walk down from the topmost ancestors to a particular node... but only assuming neither DOM has been mutated since cloning.

Otherwise, you'd be left with some horrid hack like walking the entire DOM of the clone immediately after cloning, writing an expando property to each node to refer to the source node.

I'm not sure why you are cloning nodes at all. In the process you describe, surely you could just store the live document nodes in your lists, without any cloning?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜