如何找到两个或更多节点最近的共同祖先? [英] How to find the nearest common ancestors of two or more nodes?

查看:177
本文介绍了如何找到两个或更多节点最近的共同祖先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户在HTML页面中选择两个或多个元素。我想要完成的是找到那些元素的共同祖先(如果以前没有找到,那么身体节点将是共同的祖先)?

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 found before) ?

PS:它可以用XPath,但对我来说它不是一个更好的选择。也可以通过css选择器解析找到它,但我认为它是一个脏方法(?)

P.S: It can be achieved with XPath but it is not a preferable option for me. Also it may be found with css selector parsing but i think it is a dirty method (?)

谢谢。

推荐答案

试试这个:

function get_common_ancestor(a, b)
{
    $parentsa = $(a).parents();
    $parentsb = $(b).parents();

    var found = null;

    $parentsa.each(function() {
        var thisa = this;

        $parentsb.each(function() {
            if (thisa == this)
            {
                found = this;
                return false;
            }
        });

        if (found) return false;
    });

    return found;
}

像这样使用:

var el = get_common_ancestor("#id_of_one_element", "#id_of_another_element");

这很快就会嘎嘎作响,但它应该有效。如果你想要稍微不同的东西(例如jQuery对象返回而不是DOM元素,DOM元素作为参数而不是ID等),应该很容易修改。

That's just rattled out pretty quickly, but it should work. Should be easy to amend if you want something slightly different (e.g. jQuery object returned instead of DOM element, DOM elements as arguments rather than IDs, etc.)

这篇关于如何找到两个或更多节点最近的共同祖先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆