jquery find to get the first element

前端 未结 6 1420
忘掉有多难
忘掉有多难 2020-12-29 19:11

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 on

相关标签:
6条回答
  • 2020-12-29 19:21

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

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

    Works like a charm!

    0 讨论(0)
  • 2020-12-29 19:34

    You can use either

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

    or

    $(this).closest('.comment').find('form:first').toggle('slow');
    
    0 讨论(0)
  • 2020-12-29 19:37

    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>

    0 讨论(0)
  • 2020-12-29 19:43

    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.

    0 讨论(0)
  • 2020-12-29 19:45

    Use :first selector like below :

    $(this).closest('.comment').find('form:first').toggle('slow');
    
    0 讨论(0)
  • 2020-12-29 19:47

    using jquery simply use:

        $( "form" ).first().toggle('slow');
    
    0 讨论(0)
提交回复
热议问题