Skip to content

Instantly share code, notes, and snippets.

@mwunsch
Created April 23, 2015 21:04
Show Gist options
  • Save mwunsch/29bca83eaf7649873900 to your computer and use it in GitHub Desktop.
Save mwunsch/29bca83eaf7649873900 to your computer and use it in GitHub Desktop.
createTreeWalker + createDocumentFragment = diff
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="grid-thumb" id="grid-thumb-viv9" data-style-name="VIV9">
<a class="item-link" href="/shop/designers/vivienne_westwood_anglomania/julia_dress">
<div class="grid-thumb-images">
<img class="current" alt="Vivienne%20Westwood%20Anglomania - Julia%20Dress" width="270" height="405" src="https://pc-ap.renttherunway.com/productimages/front/270x/fc/VIV9.jpg">
<img alt="Vivienne%20Westwood%20Anglomania - Julia%20Dress" width="270" height="405" src="https://pc-ap.renttherunway.com/productimages/side/270x/fc/VIV9.jpg" class="">
<img alt="Vivienne%20Westwood%20Anglomania - Julia%20Dress" width="270" height="405" src="https://pc-ap.renttherunway.com/productimages/back/270x/fc/VIV9.jpg">
</div>
<div class="grid-thumb-info ">
<div class="thumb-designer subtitle-strong upper">Vivienne Westwood Anglomania</div>
<div class="thumb-name subtitle">Julia Dress</div>
<div class="thumb-price thumb-price-default subtitle-strong">
$275
rental
</div>
<div class="thumb-retail subtitle">
$1739
retail
</div>
</div>
</a>
<div class="favorite-wrapper heart-wrapper">
<div class="thumb-heart favorite-VIV9 favorite_add s32-heart-lg-off" rel="stylename=VIV9" title="Add to Favorites"></div>
</div>
</div>
<script>
function walkerFactory(root) {
return document.createTreeWalker(
root,
NodeFilter.SHOW_ALL,
function (n) {
if (!/\S/.test(n.nodeValue)) {
return NodeFilter.FILTER_SKIP;
}
return NodeFilter.FILTER_ACCEPT;
}
);
}
var el = document.getElementById("grid-thumb-viv9"),
frag = document.createDocumentFragment(),
walker = walkerFactory(document.body),
fragWalker = walkerFactory(frag),
diffs = [],
diff;
frag.appendChild(el.cloneNode(true));
frag.querySelector(".thumb-price-default").textContent = "$285 rental";
while (walker.nextNode() && fragWalker.nextNode()) {
if (!walker.currentNode.isEqualNode(fragWalker.currentNode)) {
diffs.push([walker.currentNode, fragWalker.currentNode]);
}
}
do {
diff = diffs.pop()
if (diff[0].isEqualNode(diff[1])) break;
if (diff[0].parentNode) {
diff[0].parentNode.replaceChild(diff[1].cloneNode(true), diff[0]);
}
} while (diffs.length)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment