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

前端 未结 14 1942
-上瘾入骨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:19

    The solutions involving manually going through the ancestor elements are far more complicated than necessary. You don't need to do the loops manually. Get all the ancestor elements of one element with parents(), reduce it to the ones that contain the second element with has(), then get the first ancestor with first().

    var a = $('#a'),
        b = $('#b'),
        closestCommonAncestor = a.parents().has(b).first();
    

    jsFiddle example

提交回复
热议问题