tags:

views:

256

answers:

2

Does anyone know a good way to test if one element, stored in a var, is the child of another, also stored in a var?

I don't need element1.isChildOf('selector'), that's easy.
I need element1.isChildOf(element2)

element2.find(element1).size() > 0 Does not seem to work.

I don't want to have to write a plugin the uses .each to test each child if I can avoid it.

+3  A: 

If you're using 1.4, and are looking for a descendant rather than a child as your find() example implies, there's a has() method:

element2.has(element1).length > 0
Max Shawabkeh
`has()` checks works if something is a **descendant** and not a child as per the title.
cletus
You are correct. The `find()` example in the question misled me. Clarified.
Max Shawabkeh
Sorry, Descendant is what I'm after. I'll try this now. Cheers
Jake
Great, Thanks. I also found I did not need the `> 0` since `0 == false`
Jake
+2  A: 

You can use index() for this. It will return -1 if an element isn't in the set. Assuming element1 and element2 are DOM elements and not jQuery objects:

if ($(element2).children().index(element1) != -1) {
  // it's a child
}

For completeness, to test is something is a descendant and not just a child, it can be used for that too:

if ($(element1).parents().index(element2)) != -1) {
  // element1 is a descendant of element2
}
cletus