I’m trying to make an intelligent way to copy HTML from one element to another.
Let’s say I have the below. I want to copy the structure from “.from” to “.to”. I can copy wholesale with .html() but this is slow for a large tree, and causes a flicker as the browser redraws.
I’m wondering if anyone knows of a way I could recursively dig through each element’s tree and compare element by element. So if only one element’s HTML or attributes have changed, I only need to change that one element – everything else stays the same.
In the example below, “.a” would have unchanged attributes, but changed HTML. “.b” would need to dig into its children and change the attributes and HTML of “.x”. “.e” would have to be created in the target element.
Does anyone know of an intelligent way to do this?
<ul class="to">
<li class="a">test1</li>
<li class="b">
<div class="x">test2</div>
</li>
<li>test3</li>
<li class="c">test4</li>
</ul>
<ul class="from">
<li class="a">test5</li>
<li class="b">
<div class="y">test6</div>
</li>
<li class="c">test7</li>
<li class="d">test4</li>
<li class="e">test</li>
</ul>
Please look at my solution: http://javascripts.svn.sourceforge.net/viewvc/javascripts/javascripts/js.prototype-extensions/js/extensions/element.js?view=markup – starting from comment
Smooth update of DOM subtree, this code may be easily adopted to jQuery.In short words, function
updateSmoothlycompares two DOM subtrees (source and destination) node by node, trying to preserve existing nodes and make as minimal changes in source subtree as possible. In your example it will change text values, add/remove CSS classes of already existing text/element nodes, and append only oneLIto list.This solution is working in production environment, updating tables with 1300+ rows fast enough even in IE8.
P.S. Similar answer to another question: Updating gigantic HTML table with ajax