以下是我的 HTML:
<div id="formdata">
<div id="to_select">
<input type='hidden' name='to_be_selected' value='a' />
<input type='hidden' name='also_to_be_selected' value='a' />
</div>
<input type='hidden' name='to_be_selected_too' value='a' />
<div id="not_to_select">
<input type='hidden' name='not_to_select' value='not selected'/>
</div>
</div>
如何仅选择不在 div#not_to_select 中的元素
以下是我尝试过的:
$("#formdata div:not(#not_to_select)").find('input')
$("#formdata").not("div#not_to_select").find('input,select,textarea')
$("#formdata").find('input,select,textarea').filter(function(){
return $(this).parent().is(":not(#not_to_select)");
})
最佳答案
要实现此目的,您可以使用 filter()
排除作为 #not_to_select
后代的 inputs
:
var $inputs = $('#formdata input').filter(function() {
return $(this).closest('#not_to_select').length == 0;
});
$inputs.addClass('foo');
.foo { border: 1px solid #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="formdata">
<div id="to_select">
<input type="text" name="to_be_selected" value="a" />
<input type="text" name="also_to_be_selected" value="a" />
</div>
<input type="text" name="to_be_selected_too" value="a" />
<div id="not_to_select">
<input type="text" name="not_to_select" value="not selected" />
</div>
</div>
或者,您可以使用 :not()
来排除它们:
var $inputs = $('#formdata input:not(#not_to_select input)');
$inputs.addClass('foo');
.foo { border: 1px solid #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="formdata">
<div id="to_select">
<input type="text" name="to_be_selected" value="a" />
<input type="text" name="also_to_be_selected" value="a" />
</div>
<input type="text" name="to_be_selected_too" value="a" />
<div id="not_to_select">
<input type="text" name="not_to_select" value="not selected" />
</div>
</div>
关于javascript - jQuery 选择器除父级为 div 之外的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54133448/