2012-03-23 24 views
21
<div id="example"> 
    <div id="test"></div> 
</div> 

<div id="another">Blah</div> 

का उपयोग कर रहा $('#another').hide() सेट करना चाहते हैं लेकिन केवल तभी जब #example चाइल्ड तत्व #test कहा जाता है शामिल है संभव है? ऐसा लगता है जैसे यह होगा।जांच करें कि पेरेंट तत्व, कुछ बच्चे तत्व jQuery

उत्तर

46

उपयोग length

if ($('#example').find('#test').length) { 
    // found! 
} 
4

मुझे लगता है कि आप देख रहे हैं निम्नलिखित

if (jQuery.contains($('#example'), $('#test')) { 
    $('#another').hide(); 
} 

यह रूप में अच्छी तरह यकीन है कि मेरे सिर के ऊपर से नहीं काम कर सकते हैं, है।

if ($('#test', $('#example')).size() > 0) { 
    $('#another').hide(); 
} 
+1

'आकार()'। लंबे समय में नहीं देखा है! 'लंबाई' ftw। – elclanrs

+4

क्या 'शामिल' को डीओएम तत्व के साथ पैरामीटर के रूप में जाना चाहिए और jQuery ऑब्जेक्ट नहीं होना चाहिए? http://api.jquery.com/jQuery.contains/ – mxro

3
<script> 
    var test = $('#example #test').length(); 
    if(test !== 0){ 
     $('#another').hide(); 
    } 
</script> 
+0

'test' कभी भी 'अपरिभाषित' नहीं होगा – Esailija

+1

लंबाई फ़ंक्शन नहीं है -> लंबाई '। और यह भी झूठा है ताकि आप '! == 0' से छुटकारा पा सकें और 'if (test)' करें – elclanrs

1

jQuery पुस्तिका का उपयोग करने का सुझाव देते हैं:

if ($('#parent').has('#child').length) { 
    //do something 
} 

http://api.jquery.com/has/

संबंधित मुद्दे