Is there a way to select the first item from a set of types

I want to know if there is a way to use jQuery (in a chain) 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 exists in each div.panel.

Thus, in the example above, my jQuery selector returns a collection of three elements input#first, textarea#thirdand select#fifth.

The following loop will give me the results that I will be after, but of course there is a cleaner way according to jQuery, which can do it in one go?

var firstFormFieldList = [];

$('.panel').each(function(i, el){
   var firstEl = $(el).find('input,select,textarea').filter(':first');
   firstFormFieldList.push(firstEl);
});
+3
source share
3 answers

You are looking for a selector :input( DOCS ):

$('.panel').find(':input:first')

Example

+9
source

:input :first.

$('.panel').find(':input:first')

jsFiddle.

, , .

+3

You can do it as follows:

$('.panel').each(function(){
    alert($(this).children(':input').first().attr('id'));
});

Check and play here - http://jsfiddle.net/dhruvasagar/yLnnX/

0
source

All Articles