user2560165
user2560165

Reputation: 149

How to check all parents of the div in jquery

I have a code

  <div id="parent">
    <div>  
      <div id="child">

      </div>
    </div>
  </div>

How i can to check - is there id="child" have a parent with id="parent" ?

Upvotes: 0

Views: 114

Answers (4)

ssilas777
ssilas777

Reputation: 9764

if($('#child').parents('#parent').length > 0)
{
//true
}

Upvotes: 0

emilchristensen
emilchristensen

Reputation: 286

if ($('#child').closest('#parent').length > 0) {
    // child is inside parent
}

You check if the child has any ancestors. You can read more about the .closest() function here: jQuery docs .closest()

Upvotes: 0

mishik
mishik

Reputation: 10003

if($("#child").closest("#parent").length) {
  // Luke, I'm your father
}

These should also do:

if($("#parent #child").length) {
  // Noooooooo!
}
if($("#parent").find("#child").length) {
  // May the force be with you
}
if($("#parent:has(#child)").length) {
  // Very powerful jQuery selector has become
}

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

if($('#child').closest('#parent').length){
  // yes... child is inside parent
}

Upvotes: 0

Related Questions