views:

58

answers:

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...
}
+1  A: 

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).

cletus
Very tidy - I may have to get some jquery on the case in this project, starting to look worth it now.
sanchothefat
@sanchothefat oh my bad, sorry for some reason I thought your question was jQuery-related.
cletus
No worries. Pretty much all javascript is jquery related these days (or should be)
sanchothefat
+4  A: 

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).

Alsciende
Thanks for the library free version though you've both been a big help!
sanchothefat
+1  A: 

// 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;
 }
}
kennebec