Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<div data-x="foo" class="bar"><span data-x="foo"class="bar">x</span><s</div>
<div class="bar" data-x="foo"><span class="bar" data-x="foo">xy</span></div>
 
jQuery(function($) {
  
  function getAttributeNames(node) {
    var index, rv, attrs;
    
    rv = [];
    attrs = node.attributes;
    for (index = 0; index < attrs.length; ++index) {
      rv.push(attrs[index].nodeName);
    }
    rv.sort();
    return rv;
  }
  
  function equivElms(elm1, elm2) {
    var attrs1, attrs2, name, node1, node2;
    
    // Compare attributes without order sensitivity
    attrs1 = getAttributeNames(elm1);
    attrs2 = getAttributeNames(elm2);
    if (attrs1.join(",") !== attrs2.join(",")) {
      display("Found nodes with different sets of attributes; not equiv");
      return false;
    }
    
    // ...and values
    // unless you want to compare DOM0 event handlers
    // (onclick="...")
    for (index = 0; index < attrs1.length; ++index) {
      name = attrs1[index];
      if (elm1.getAttribute(name) !== elm2.getAttribute(name)) {
        display("Found nodes with mis-matched values for attribute '" + name + "'; not equiv");
        return false;
      }
    }
    
    // Walk the children
    for (node1 = elm1.firstChild, node2 = elm2.firstChild;
         node1 && node2;
         node1 = node1.nextSibling, node2 = node2.nextSibling) {
       if (node1.nodeType !== node2.nodeType) {
         display("Found nodes of different types; not equiv");
         return false;
       }
       if (node1.nodeType === 1) { // Element
         if (!equivElms(node1, node2)) {
           return false;
         }
       }
       else if (node1.nodeValue !== node2.nodeValue) {
         display("Found nodes with mis-matched nodeValues; not equiv");
         return false;
       }
    }
    if (node1 || node2) {
      // One of the elements had more nodes than the other
      display("Found more children of one element than the other; not equivalent");
      return false;
    }
    
    // Seem the same
    return true;
  }
    
  var divs = $("div");
  display("Equiv? " + equivElms(divs[0], divs[1]));
  
  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers