3

My question is exactly that but in context I want to examine the selection object, compare the anchorNode and focusNode and if they are different then find the first common parent element.

var selected = window.getSelection();
var anchor = selection.anchorNode;
var focus = selection.focusNode;

if ( anchor != focus ) {
   // find common parent...
}

5 Answers 5

11

Since this question and accepted answer are very dated, I'd like to suggest using a more modern DOM API, Range:

function findFirstCommonAncestor(nodeA, nodeB) {
    let range = new Range();
    range.setStart(nodeA, 0);
    range.setEnd(nodeB, 0);
    // There's a compilication, if nodeA is positioned after
    // nodeB in the document, we created a collapsed range.
    // That means the start and end of the range are at the
    // same position. In that case `range.commonAncestorContainer`
    // would likely just be `nodeB.parentNode`.
    if(range.collapsed) {
        // The old switcheroo does the trick.
        range.setStart(nodeB, 0);
        range.setEnd(nodeA, 0);
    }
    return range.commonAncestorContainer;
}
1
  • 1
    For those of you wondering about browser support for Range, even IE9 supports it, thats how long ago (around 2012) it was implemented in browser: caniuse.com/mdn-api_range Nov 21, 2022 at 7:18
7

I would try something like this, assuming no JS library:

function findFirstCommonAncestor(nodeA, nodeB, ancestorsB) {
    var ancestorsB = ancestorsB || getAncestors(nodeB);
    if(ancestorsB.length == 0) return null;
    else if(ancestorsB.indexOf(nodeA) > -1) return nodeA;
    else if(nodeA == document) return null;
    else return findFirstCommonAncestor(nodeA.parentNode, nodeB, ancestorsB);
}

using this utilities:

function getAncestors(node) {
    if(node != document) return [node].concat(getAncestors(node.parentNode));
    else return [node];
}

if(Array.prototype.indexOf === undefined) {
    Array.prototype.indexOf = function(element) {
        for(var i=0, l=this.length; i<l; i++) {
            if(this[i] == element) return i;
        }
        return -1;
    };
}

Then you can call findFirstCommonAncestor(myElementA, myElementB).

1
  • Thanks for the library free version though you've both been a big help!
    – roborourke
    Mar 16, 2010 at 11:26
1

This way is fairly straightforward:

var fp = $(focus).parents();
var ap = $(anchor).parents();
for (var i=0; i<ap.length; i++) {
  if (fp.index(ap[i]) != -1) {
    // common parent
  }
}

Loop through the parents() of one element and see if they are contained in the parents() of the other using index() until you find a match (or not).

3
  • Very tidy - I may have to get some jquery on the case in this project, starting to look worth it now.
    – roborourke
    Mar 16, 2010 at 11:27
  • @sanchothefat oh my bad, sorry for some reason I thought your question was jQuery-related.
    – cletus
    Mar 16, 2010 at 11:45
  • No worries. Pretty much all javascript is jquery related these days (or should be)
    – roborourke
    Mar 17, 2010 at 11:47
1

// It seems like it should be fairly simple, even without a library or indexOf

document.commonParent= function(a, b){
 var pa= [], L;
 while(a){
  pa[pa.length]=a;
  a= a.parentNode;
 }
 L=pa.length;
 while(b){  
  for(var i=0; i<L; i++){
   if(pa[i]==b) return b;
  }
  b= b.parentNode;
 }
}
1

There is a a good bit of DOM API for that: compareDocumentPosition

This is how it goes:

    /**
     * Returns closest parent element for both nodes.
     */
    function getCommonParent(one, two){
        let parent = one.parentElement;
        if(one === two) { //both nodes are the same node.
            return parent;
        }
        const contained = Node.DOCUMENT_POSITION_CONTAINED_BY;
        let docpos = parent.compareDocumentPosition(two);

        while(parent && !(docpos & contained)) {
            parent = parent.parentElement;
            docpos = parent.compareDocumentPosition(two);
        }
        return parent;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.