Home » Jquery » jQuery test if element1 is descendant of element2

jQuery test if element1 is descendant of element2

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

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

Questions:
Answers:

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
}

Questions:
Answers:

As of Jquery 1.6 you can determine whether a jquery object is a child of another jquery object this way:

element2.is(element1.children());

Also notable, since is() now accepts several different arguments (the first argument can be a function, jQuery selector, or DOM element), you can’t think of the it simply as “is” anymore, but rather “is or is in”.

Questions:
Answers:

I know this thread is old but this also works if you want to check upwards not downwards:

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

Here is a working example

Questions:
Answers:

This is true if element1 is the child of element2, in other words element1 has a parent, that is element2

$(element1).parents(element2).length 

this way it is not OK, if the parent has more children (let say they are input‘s):

$(element2).children(element1).length