JQuery test if element1 is a descendant of element2

Does anyone know of a good way to check if one element stored in var is a descendant of another also stored in var?

I don't need element1.isChildOf('selector') , it's simple.
I need element1.isChildOf(element2)

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

I do not want to write a plugin to use .each to check each child if I can avoid it.

+41
jquery
Mar 08 2018-10-10T00:
source share
5 answers

If you use 1.4 and are looking for a descendant, not a child, as your find() example find() , there has() :

 element2.has(element1).length > 0 
+71
Mar 08
source share

You can use index() for this. It will return -1 if the item is not in the set. Assuming element1 and element2 are DOM elements, not jQuery objects:

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

For completeness, to check if something is a descendant, and not just a child, it can also be used for this:

 if ($(element1).parents().index(element2) != -1) { // element1 is a descendant of element2 } 
+7
Mar 08
source share

As of jQuery 1.6, you can determine if a jquery object is a child of another jquery object this way:

 element2.is(element1.children()); 

Also noteworthy, since is() now accepts several different arguments (the first argument can be a function, a jQuery selector, or a DOM element), you cannot think of it simply as "is", but rather of whether it is or is in ".

+6
Sep 21 '11 at 20:28
source share

I know this thread is outdated, but it also works if you want to check up not down:

 function isElementChildOf(childElement, parentElement) { return 0 !== $(childElement).parents(parentElement).length; } 

Here is a working example

+1
Jun 02 2018-12-12T00:
source share

This is true if element1 is a child of element2, in other words element1 has a parent, i.e. element2

 $(element1).parents(element2).length 

thus it is not ok if the parent has more children ( let them say that they are input ' ):

 $(element2).children(element1).length 
+1
Jun 05 2018-12-12T00:
source share



All Articles