How to find the nearest common ancestors of two or more nodes?

前端 未结 14 1947
-上瘾入骨i
-上瘾入骨i 2020-11-30 04:03

Users selects two or more elements in a HTML page. What i want to accomplish is to find those elements\' common ancestors (so body node would be the common ancestor if none

14条回答
  •  既然无缘
    2020-11-30 04:26

    Here is a dirtier way of doing this. It's easier to understand but requires dom modification:

    function commonAncestor(node1,node2){
            var tmp1 = node1,tmp2 = node2;
            // find node1's first parent whose nodeType == 1
            while(tmp1.nodeType != 1){
                tmp1 = tmp1.parentNode;
            }
            // insert an invisible span contains a strange character that no one 
            // would use
            // if you need to use this function many times,create the span outside
            // so you can use it without creating every time
            var span = document.createElement('span')
                , strange_char = '\uee99';
            span.style.display='none';
            span.innerHTML = strange_char;
            tmp1.appendChild(span);
            // find node2's first parent which contains that odd character, that 
            // would be the node we are looking for
            while(tmp2.innerHTML.indexOf(strange_char) == -1){
                tmp2 = tmp2.parentNode; 
            }                           
            // remove that dirty span
            tmp1.removeChild(span);
            return tmp2;
        }
    

提交回复
热议问题