2017-07-04 54 views

回答

2

试试这个:

$(function() { 
    $("#check").click(function(){ 
    if ($(".child").parents("#mainDiv").length == 1)  
    { 
     // the child element is inside the parent 
    } 
    else 
    { 
      //it is not inside 
    } 
    }); 
}); 

希望它是有用的

+0

这对我来说非常合适。谢谢。 –

0

您正在寻找父母内的子元素。这意味着你知道父元素已经存在。所以,你应该使用jQuery上下文选择作为

$(function() { 
    $("#check").click(function(){ 
     // exist or not 
     if($('.child', '#mainDiv').length) { 
      console.log('Yes!! element exists'); 
     } else { 
      console.log('Nope!!'); 
     } 
    }); 
}); 

您还可以使用$('#mainDiv').find('.child').length检查它是否包含child类的元素。

您可以在上下文选择器上找到更多详细信息,位于http://www.tutorialsteacher.com/jquery/jquery-selectors