Javascript DOM tree duplicate for manipulation

2020-03-03 08:05发布

Since the DOM tree of a page is active and always reflected in the browser, what is the best way to modify this DOM tree for some purpose without affecting the actual rendered tree ? Let's say my purpose is to swap certain children nodes and see how similar the DOM tree still remains.

Is creating a duplicate tree the only solution ? If it is, is there a function to do this ? Or do I need to write my own function to create a duplicate copy of the tree. I won't need all the attributes of the element object, so I can create a simpler object with a few attributes that point to the siblings and children.

3条回答
贪生不怕死
2楼-- · 2020-03-03 08:40

You can use document.cloneNode(true), or the same method on another node. cloneNode clones any node, and the true means it should be recursive (deep). Obviously, this could have a significant performance cost on a large page.

查看更多
够拽才男人
3楼-- · 2020-03-03 08:56

Maybe consider one the many great JavaScript librarys out there, e.g. jQuery. These allow you to easily copy parts of or even the whole DOM of an document and have that stored appart from the DOM.

If you need to roll your own solution, a good point to start is Resig's post on document fragments: http://ejohn.org/blog/dom-documentfragments/.

Good luck.

查看更多
时光不老,我们不散
4楼-- · 2020-03-03 09:04

If you are willing to use jQuery:

var clone = $("selectorForSomeElement(s)").clone();

clone now is a copy of the element structure.

You can then work off of clone to do whatever experimenting you like.

查看更多
登录 后发表回答