check if there is a <select> within the parent div
How can I d开发者_C百科o something like this: check if I have a <select>
within the parent div, if there is one, I display something.
Thanks!
One way would be to filter with the :has
selector
if ( $(this).parent(':has(select)').length ){
// display something..
}
If on the other hand the select
is not deeper than the current element, you might want to use the .siblings()
method
if ( $(this).siblings('select').length ){
// display something..
}
If there is one, the length of the jQuery object containing matched elements is > 0
. Because if
clauses get executed when the condition is 'truthy' (everything except values like 0
, undefined
etc) you are safe to eliminate the > 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/
Yes, check the length property of the result set array.
if ($('#parentDiv select').length > 0) {
alert('There is at least one <select> inside the div!');
}
jsFiddle Working Example.
with jquery you can select nested elements.
try something like this.
if( 0 < $('select', $('#div_id') ).length ) {
alert( 'Select box in the div' );
} else {
alert( 'NO Select box in the div' );
}
You can also use function closest
<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>
精彩评论