检查父div中是否有<select> </select>

时间:2011-08-13 16:21:31

标签: javascript jquery html

我该如何做这样的事情:检查父div中是否有<select>,如果有,我会显示一些内容。

谢谢!

5 个答案:

答案 0 :(得分:8)

一种方法是使用:has选择器

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

如果另一方面select不比当前元素深,则可能需要使用.siblings()方法

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

答案 1 :(得分:7)

如果有,则包含匹配元素的jQuery对象的长度为> 0。因为if条款在条件为“真实”(除0undefined等值之外的所有内容)时执行,您可以安全地删除> 0

if($(this).parent().find("select").length) {
    // there is one, display something
}

http://api.jquery.com/length/

http://api.jquery.com/parent/

http://api.jquery.com/find/

答案 2 :(得分:1)

是,检查结果集数组的length属性。

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

<强> jsFiddle Working Example

答案 3 :(得分:1)

使用jquery可以选择嵌套元素。

尝试这样的事情。

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

答案 4 :(得分: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>
相关问题