我需要帮助来使用jQuery选择每个孩子的第一个孩子。
.children()。children()将全选
.children()。first()不起作用
$(function(){
$('.form').each(function(){
$(this).children().children().addClass('some class');
});
});
<form class="form">
<div>
<label>I need select this</label>
<label><input type="checkbox"> do not select this</label>
</div>
<div>
<label>I need select this</label>
<input type="text">
</div>
</form>
感谢所有解决方案,我选择了以下解决方案:
$(this).children().children(':first-child')...
答案 0 :(得分:1)
$(function(){
$('.form').each(function(){
$(this).children().children(':first-child').addClass('colorclass');
});
});
.colorclass{
background-color:yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
<div>
<label>1st child</label>
<label><input type="checkbox"> do not select this</label>
<div>
<label>Grand child</label>
<label><input type="checkbox"> do not select this</label>
</div>
</div>
<div>
<label>2nd child</label>
<input type="text">
<div>
<label>2nd Grand child</label>
<input type="text">
</div>
</div>
</form>
答案 1 :(得分:0)
请尝试以下操作:
虽然:first只匹配一个元素,但是:first-child选择器可以匹配多个:每个父代都可以匹配一个。这等效于:nth-child(1)。
$(function(){
$('.form').each(function(){
$(this).find('div :first-child').addClass('some class');
});
});
<form class="form">
<div>
<label>I need select this</label>
<label><input type="checkbox"> do not select this</label>
</div>
<div>
<label>I need select this</label>
<input type="text">
</div>
</form>
这应该有帮助。
答案 2 :(得分:0)
.children()将为您提供所有childNode的数组。
您要遍历所有表单元素,需要遍历表单的子项
$(function() {
$('.form').children().each(function() {
$(this).children().first().addClass('some class')
});
});
.some.class {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
<div>
<label>I need select this</label>
<label><input type="checkbox"> do not select this</label>
</div>
<div>
<label>I need select this</label>
<input type="text">
</div>
</form>
答案 3 :(得分:0)
有两种向标签元素添加类的方法。
// 1. you can directly add label within selector
$(function(){
$('.form div label').each(function(){
$(this).addClass('some class');
});
});
// 2. second method as per your need is
$(function(){
$('.form').each(function(){
$(this).children().first().addClass('some class');
});
});