2017-07-04 55 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