I'm new to JavaScript and am trying to create a recursive function that checks if two DOM nodes are equivalent. This function seems to be returning true for everything and isn't checking the DOM the way I want it to for some reason. Only nodes 1 & 4 are equivalent.
var htmlStrings = ['<div id="one">Some<span>node <em>contents</em> for</span>comparison</div>', '<div id="two">Some<span>node contents for</span>comparison</div>', '<div id="one">Some<span>node <strong>contents</strong> for</span>comparison</div>', '<div id="four">Some<span>node <em>contents</em> for</span>comparison</div>'];
var div1 = document.createElement('div');
div1.innerHTML = htmlStrings[0];
document.body.appendChild(div1);
var div2 = document.createElement('div');
div2.innerHTML = htmlStrings[1];
document.body.appendChild(div2);
var div3 = document.createElement('div');
div3.innerHTML = htmlStrings[2];
document.body.appendChild(div3);
var div4 = document.createElement('div');
div4.innerHTML = htmlStrings[3];
document.body.appendChild(div4);
function nodeEquivalence(node1, node2) {
var passed = false;
if (node1.nodeType === node2.nodeType) {
if ((node1.tagName === node2.tagName && node1.nodeValue === node2.nodeValue)) {
passed = true;
}
}
node1 = node1.firstChild;
node2 = node2.firstChild;
while (node1 && node2) {
nodeEquivalence(node1, node2);
node1 = node1.nextSibling;
node2 = node2.nextSibling;
}
return passed;
}
console.log(nodeEquivalence(div1, div2));
console.log(nodeEquivalence(div1, div4));