2

Is there any way to find whether an element is a parent or ancestor of other.

I have searched the jquery and found the below method. But here we cant use any java script plain object or jquery object.

$.contains( document.documentElement, document.body ); // true 

How to validate? Please suggest.

4 Answers 4

3

Check if the number of children are there:

contains = function (parent, child) { if ( $(parent).find(child).length > 0) { return true; } else { return false; } } 

Use this way:

contains("body", ".check"); 
Sign up to request clarification or add additional context in comments.

Comments

2

Using .closest() you can traverse up the DOM tree. If the length returned is greater than 0 then a parent/ancestor has been found.

For example:

if ($(".child").closest(".parent").length){ alert("parent / ancestor found"); } 

http://jsfiddle.net/dqactw0a/1/

5 Comments

This will always return true. Won't it? Can you demonstrate a place where this doesn't alert?
When there is no .parent element which is a parent of .child.
Sorry, I took it in a generic way. :)
It is probably more efficient to use closest() instead of parents()... but we are talking about tiny amounts of performance here, so it's not much of an issue
Just for reference, here is a performance test
0

One option would be to select the element, for example

if ( $('#parent .child').length ) { // the element #parent is a parent or ancestor of .child } else { // the element #parent is NOT a parent or ancestor of .child } 

2 Comments

what if the children element has no child class ?
lenght will be 0 which is false(ey), so this will work correctly. Maybe brush up on javascript before downvoting
-1
if ($('#div1').children().length > 0) { alert('i'm a parent div') } 

The children() function returns that object has children or not. use can use it to check whether the element is parent or not.

3 Comments

would'nt this just check if a element has any children, not if a element has a specified child?
@atmd: before downvote, did you read the question ? whether an element is a parent or ancestor. not asking for any specific child.
I did'nt downvote, also "element is a parent or ancestor of other" suggest a specified parent and child

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.