Reputation: 149
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
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
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
Reputation: 44740
if($('#child').closest('#parent').length){
// yes... child is inside parent
}
Upvotes: 0