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

前端 未结 14 1975
-上瘾入骨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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 04:24

    did not liked any of the answers above(want pure javascript and one function). that worked perfectly for me,efficient and also easier to understand:

        const findCommonAncestor = (elem, elem2) => {
          let parent1 = elem.parentElement,parent2 = elem2.parentElement;
          let childrensOfParent1 = [],childrensOfParent2 = [];
          while (parent1 !== null && parent2 !== null) {
            if (parent1 !== !null) {
              childrensOfParent2.push(parent2);
              if (childrensOfParent2.includes(parent1)) return parent1;
            }
            if (parent2 !== !null) {
              childrensOfParent1.push(parent1);
              if (childrensOfParent1.includes(parent2)) return parent2;
            }
            parent1 = parent1.parentElement;
            parent2 = parent1.parentElement;
          }
          return null;
        };
    
    

提交回复
热议问题