I want to know if there is a way use jQuery (in a chaining fashion) to select the following:
<div class="panel">
<input id="first" type="text" />
<input id="second" type="text" />
</div>
<div class="panel">
<h2>Panel title</h2>
<textarea id="third"></textarea>
<input id="fourth" type="text" />
</div>
<div class="panel">
<p>Some paragraph</p>
<select id="fifth"></select>
<input id="sixth" type="text" />
</div>
I would like to select the first form element (i.e. either input
/select
/textarea
) that exist in each div.pa开发者_JAVA技巧nel
.
So in the above example, my jQuery selector would return a collection of three elements: input#first
, textarea#third
and select#fifth
.
The following loop will get me the results that I am after, but surely there is a cleaner way in line with jQuery that can do this in one go?
var firstFormFieldList = [];
$('.panel').each(function(i, el){
var firstEl = $(el).find('input,select,textarea').filter(':first');
firstFormFieldList.push(firstEl);
});
You're looking for the :input
selector (DOCS):
$('.panel').find(':input:first')
Example
Use :input
and :first
.
$('.panel').find(':input:first')
jsFiddle.
You must split up the selector, otherwise it will only find the first input element, not the first of each.
You can do it like this :
$('.panel').each(function(){
alert($(this).children(':input').first().attr('id'));
});
Check & play with it here - http://jsfiddle.net/dhruvasagar/yLnnX/
精彩评论