tags:

views:

152

answers:

2

I want to find out if DOM element a contains DOM element b (that is, if a is an ancestor of b in the DOM tree). Thus, something like:

$(b).closest(a);

but where 'a' is a DOM node here, not a selector.

Can jQuery help with that? All the useful functions I can find take selector strings rather than elements, which doesn't really help if your DOM element is anonymous.

A: 

Aha, I failed miserably with searching but a coworker found the answer is already around at http://stackoverflow.com/questions/287875/testing-objects-for-ancestor-descendent-relationship-in-javascript-or-jquery but the question was asked in such a different way that I didn't find it:

if ($(obj1).parents().index(obj2) >= 0) {
    // obj1 is a descendant of obj2
}

Still not as efficient as I'd expect, though ('find all the parents and then check for a match' versus 'step up the tree looking for a match').

There's also http://plugins.jquery.com/project/ancestry, which provides exactly the functions I'm talking about.

Update:

if($(obj1).parents.eq(obj2)) { ...

also works and is marginally neater. The parent list is unlikely to be that long so this should be fairly efficient.

ijw
jQuery find() method is more appropriate for this purpose.
Technowise
"$(parent).find("... er, what? If what you have is an unnamed DOM node, then you can't make the selector it requires as an argument, unless I'm missing something.
ijw
+1  A: 

Here is the docs for Traversing. I recomend you using:

  • find() to find descendents of a specific type, maybe starting from document itself
  • parents() to find parents of specific type in the DOM tree starting from an x element
Elzo Valugi
As I said, ... "where 'a' is a DOM node here, not a selector"
ijw
are you talking about this? https://developer.mozilla.org/En/XBL/XBL_1.0_Reference/Anonymous_Content
Elzo Valugi
No, I'm talking about a DOM node for which I have a reference but no selector. To me, it's just a reference. And it's hard to turn that reference into a selector because it may not have an ID - that is, it's nameless, or anonymous.
ijw
you don't need an ID to identify DOM elements. Traversing function do that in jQuery, and you can access each element in the DOM without being explicitly identified. Actually when you do $(b) you already have a jQuery object wrapped over your DOM object. http://docs.jquery.com/Core/jQuery#elements. This means that you can use this functions without any problems.
Elzo Valugi