Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery test if element1 is descendant of element2

Tags:

jquery

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.

like image 895
Jake Avatar asked Mar 08 '10 01:03

Jake


2 Answers

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 
like image 175
Max Shawabkeh Avatar answered Sep 22 '22 16:09

Max Shawabkeh


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 } 
like image 23
cletus Avatar answered Sep 19 '22 16:09

cletus