views:

41

answers:

2

Hi, 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) ?

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 (?)

Thank you.

+3  A: 

You should be able to use the jQuery .parents() function and then walk through the results looking for the first match. (Or I guess you could start from the end and go backwards until you see the first difference; that's probably better.)

Pointy
To compare each element I recomend you to make a separated function. It is not so easy. The simple way (not so nice) is to compare the innerhtml of each element. The hardest (but pretty nice) is to start comparing the ids. If they are both undefined, compare the clases, if both elements have same classes (be carefull with classe's order) then you can compare the elements indexes in the body.
Diego
@Diego: a straight comparison between two DOM elements should be all you need, I believe
Bobby Jack
@Diego because any DOM element actually in the DOM (which will be true for all the parents of an element in the DOM) only exists once, even two separate jQuery arrays will have references to the exact same objects. Thus, a simple `===` comparison should work fine.
Pointy
+2  A: 

Try this:

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

Use it like this:

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

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

Bobby Jack
i prepared a test case and your solution works. Thanks.
Ozgur