Does anyone know a good way to test if one element, stored in a var, is the descendant 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.
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
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 if something is a descendant and not just a child, it can also be used for that too:
if ($(element1).parents().index(element2) != -1) { // element1 is a descendant of element2 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With