jquery find to get the first element

Viewed 87011

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>
7 Answers

You can use either

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

or

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

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.

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

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

Works like a charm!

Use the below example for jquery find to get the first element

More filtring methods With Demo

$(document).ready(function(){
  $(".first").first().css("background-color", "green");
});
.first{
    padding: 15px;
    border: 12px solid #23384E;
    background: #28BAA2;
    margin-top: 10px;
}
<!DOCTYPE html>
<html>
<head>
<title>jQuery First Method Example By Tutsmake</title> 
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
 
<h1>This is first() method example</h1>
 
<div class="first">
  <p>A paragraph in a div.</p>
  <p>Another paragraph in a div.</p>
</div>
<br>
 
<div class="first">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>
<br>
 
<div class="first">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>
 
</body>
</html>

you can use like this

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