Skip to content

Instantly share code, notes, and snippets.

@dfreedm
Created January 29, 2014 01:49
Show Gist options
  • Select an option

  • Save dfreedm/8680278 to your computer and use it in GitHub Desktop.

Select an option

Save dfreedm/8680278 to your computer and use it in GitHub Desktop.
Normalize
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>polyfill node.normalize()</title>
</head>
<body>
<div id="work">
foo
<span></span>
baz
</div>
<script>
var work = document.querySelector('#work');
work.firstElementChild.appendChild(document.createTextNode('buzz'))
work.firstElementChild.appendChild(document.createTextNode('quux'))
var work2 = work.cloneNode(work);
function normalize(node) {
var temp = '';
var cn = Array.prototype.slice.call(node.childNodes, 0), l = cn.length, n, i;
for (i = 0; (i < l) && (n = cn[i]); i++) {
if (n.nodeType === Node.TEXT_NODE) {
temp += n.textContent;
node.removeChild(n);
} else {
node.insertBefore(document.createTextNode(temp), n);
temp = '';
if (n.childNodes.length) {
normalize(n);
}
}
}
if (temp.length) {
node.appendChild(document.createTextNode(temp));
}
}
work.normalize();
normalize(work2);
function structCompare(a, b) {
var ret = a && b;
ret = ret && a.nodeType === b.nodeType;
ret = ret && a.childNodes.length === b.childNodes.length;
ret = ret && a.textContent === b.textContent;
for (var i = 0; i < a.childNodes.length; i++) {
ret = ret && structCompare(a.childNodes[i], b.childNodes[i]);
}
return ret;
}
console.log(structCompare(work, work2));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment