Reputation: 2278
I need help to use jQuery to select the first kid of each kid.
.children().children() will select all
.children().first() does not work
$(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>
Thanks all now solved, i picked this solution:
$(this).children().children(':first-child')...
Upvotes: 0
Views: 1198
Reputation: 84
There were two way to add class to label element.
// 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');
});
});
Upvotes: 1
Reputation: 18192
$(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>
Upvotes: 1
Reputation: 192
Please, try this:
While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :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>
This should help.
Upvotes: 0
Reputation: 538
.children() will give you array of all the childNodes.
You are iterating on the all the form elements, you need to iterate over children of the form
$(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>
Upvotes: 0