Hady
Hady

Reputation: 2674

Is there a way to select the first element from a collection of types

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.panel.

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);
});

Upvotes: 3

Views: 141

Answers (3)

Dhruva Sagar
Dhruva Sagar

Reputation: 7307

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/

Upvotes: 0

alex
alex

Reputation: 490453

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.

Upvotes: 3

mVChr
mVChr

Reputation: 50205

You're looking for the :input selector (DOCS):

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

Example

Upvotes: 9

Related Questions