开发者

jquery 'contains' for DOM elements rather than selectors

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). Thu开发者_运维百科s, 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.


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


Aha, I failed miserably with searching but a coworker found the answer is already around at 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜