user34537
user34537

Reputation:

jquery find to get the first element

I am writing $(this).closest('.comment').find('form').toggle('slow'); and the problem is each of the forms in the child is being toggled. I would like only the first form to be toggled. the html is something like the below and this is the a link

<div comment>
<a href>
<form>
</form>
    <a href>
    <div comment>
    <form>
    </form>
    </div>
</div>

Upvotes: 45

Views: 101719

Answers (7)

esenkaya
esenkaya

Reputation: 408

Since find get array of form elements the first one would be [0]. I would do this to make sure to get the first one.

$(this).closest('.comment').find('form')[0].toggle('slow');

Upvotes: 0

Niraj Patel
Niraj Patel

Reputation: 115

you can use like this

$(this).find('>.comment').find('>form').toggle('slow');

Upvotes: 0

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3229

Use :first selector like below :

$(this).closest('.comment').find('form:first').toggle('slow');

Upvotes: 14

Aleksandar
Aleksandar

Reputation: 4144

The simplest way to get the first result of find is with good old [index] operator:

$('.comment').find('form')[0];

Works like a charm!

Upvotes: 1

Olivier Royo
Olivier Royo

Reputation: 840

using jquery simply use:

    $( "form" ).first().toggle('slow');

Upvotes: 8

nikola
nikola

Reputation: 2281

I use

$([selector]).slice(0, 1)

because it's the most explicit way to select a slice of a query and because it can be easily modified to match not the first element but the next, etc.

Upvotes: 5

nickf
nickf

Reputation: 546035

You can use either

$(this).closest('.comment').find('form').eq(0).toggle('slow');

or

$(this).closest('.comment').find('form:first').toggle('slow');

Upvotes: 69

Related Questions