I was confronted with a similar problem a few weeks ago and solved it
by borrowing
some code from the YUI library. So I composed this little plugin:

(function($) {
    $.fn.extend({
        isAncestor: function(descEl) {
            var ancEl = this[0];
            if (ancEl.contains) {
                return ancEl.contains(descEl);
            } else if (ancEl.compareDocumentPosition) {
                return !!(ancEl.compareDocumentPosition(descEl) & 16);
            } else {
                while (descEl = descEl.parentNode) {
                    if (descEl == ancEl)
                        return true;
                }
                return false;
            }
        }
    });
})(jQuery);

The function returns true if the first element of a jQuery object is
an ancestor of the passed element.
In your example:

$("#1").isAncestor($("#2")[0]) ---> true

Hope this is helpful for someone.


On May 8, 4:21 pm, "Dan G. Switzer, II" <[EMAIL PROTECTED]>
wrote:
> Karl,
>
> >Yeah, it's also strange that while this doesn't work:
> >     $("body > ul > li").filter($li[0]);
>
> >this does:
> >    $("body > ul > li").not($li[0]);
>
> >I'm a little lost by your parents example, though. Not sure exactly
> >what you're trying to get (esp. since you don't show where you've
> >declared $el and $parent.
>
> Let's say you have:
>
> <ul>
>         <li id="1">
>                 Parent 1
>                 <ul>
>                         <li id="2">
>                                 Child 1
>                         </li>
>                 </ul>
>         </li>
> </ul>
>
> What I want to do is see if "Child 1" has "Parent 1" somewhere in it's
> parent path. I don't really care if "Child 1" would be a child of a child of
> a child, just that at some point "Parent 1" was actually in the parent path.
>
> So, I would expect to be able to do:
>
> var $p = $("#1");
> $("#2").parents($p);
>
> Well this does work:
> $("#2").parents("#1");
>
> It doesn't work for me, since the actually "expression" I need to check
> against a jQuery object that can't be reliable queried through a pure
> CSS-style selector.
>
> >couldn't you do something like
> >$el.parent() ?
> >or $el.parent('.someclass') ?
> >or $el.parents('.someclass:first') ?
>
> >(just using class in the parents filter because not sure what you're
> >after).
>
> As I stated, using a CSS expression doesn't work for me because I'm actually
> checking to see if another jQuery object is somewhere in the parent's tree.
>
> -Dan

Reply via email to