Get Common Ancestor Function

One way to improve the dispatch technique from last week is to only attach the single listener to the greatest common ancestor of all elements that we are dispatching. To achieve this, the following method to find the common ancestor of two elements was needed:

Example 1: Get Common Ancestor Function

YAHOO.util.Dom.getCommonAncestor = function(elem1, elem2) {
    var node1 = YAHOO.util.Dom.get(elem1),
         node2 = YAHOO.util.Dom.get(elem2);

    if (! (node1 && node2)) {return null;} // missing parameter, fail
    node1 = node1.parentNode;

    // iterate up the DOM tree
    while (node1) {
        if (YAHOO.util.Dom.isAncestor(node1, node2)) {return node1;}
        node1 = node1.parentNode;
    }
    
    return null;
};

This method requires two parameters, two elements to compare. It iterates through the ancestors of the first node and leverages the existing YUI isAncestor method to check if the current ancestor of node1 is also an ancestor of node2, returning the that node. When an ancestor is not found, the method returns null. The null state can happen when one of the elements has not been add to the document yet or belongs to another window.