JSFiddle - React, Tailwind, and code Playground

by Fareez Ahmed

HTML

<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="three">
    Some
    <span>node <strong>contents</strong> for</span>
    comparison
</div>

<div id="four">
    Some
    <span>node <em>contents</em> for</span>
    comparison
</div>

JavaScript

/**
 * Using the specified DOM APIs, write a function to determine
 * whether the contents of two DOM nodes are equivalent by
 * comparing tag names and the text of nodes (ignore attributes)
 *
 * DOM APIs:
 *   * node.childNodes - an array-like object of child nodes
 *   * node.nodeType - a number indicating the type of node:
 *                     1 is an element, 3 is a text node
 *   * node.tagName - for elements, a string containing the
 *                    tag name
 *   * node.nodeValue - for text nodes, the text contained
 *                      within the node
 *
 * The function should return true if the nodes and their
 * contents are equal and false if they are not.
 *
 * Please DO NOT run the code while writing your solution.
 *
 * Some nodes have been provided for comparison once you
 * have completed your solution. Only "one" and "four" are
 * equal.
 */


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) {
    //better to assume is true, prove false, more scalable. better to return true/false than have a mutable variable.  
    //base case:
    if (node1.nodeType !== node2.nodeType || node1.tagName !== node2.tagName || node1.nodeValue !== node2.nodeValue) {
        return false;
    }
    //part of the same...