2011-08-13 20 views

回答

8

一種方法是使用:has選擇器進行過濾器

if ($(this).parent(':has(select)').length){ 
    // display something.. 
} 

如果另一方面select並不比目前的元素越深,你可能想使用.siblings()方法

if ($(this).siblings('select').length){ 
    // display something.. 
} 
1

是的,檢查結果集數組的長度屬性。

if ($('#parentDiv select').length > 0) { 
    alert('There is at least one <select> inside the div!'); 
} 

jsFiddle Working Example

+0

更正答案和榜樣。 –

1

使用jQuery,您可以選擇嵌套的元素。

嘗試這樣的事情。

if(0 < $('select', $('#div_id')).length) { 
    alert('Select box in the div'); 
} else { 
    alert('NO Select box in the div'); 
} 
0

您還可以使用功能最接近

<html> 
<script src="jquery.js"></script> 
<script> 
$(document).ready(function(){ 
    if($("#txt").closest("div").find("select").length){ 
     alert("Found it");  
    } 
}); 
</script> 
<div> 
    <select id="heart"><option value="Hello"></option></select> 
    <input type="text" id="txt" /> 
</div> 
</html>