Thursday, November 20, 2025
HomeLanguagesJavascriptjQuery first() Method

jQuery first() Method

The first() is an inbuilt function in jQuery which is used to select the first element from the specified elements. 
Syntax: 
 

$(selector).first()

Here selector is the main class of all the elements.
Parameters: It does not accept any parameter.
Return value: It returns the first element out of the selected elements.
jQuery code to show the working of this function: 
Code #1: 
 

html




<html>
  
<head>
               jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("div").first().css("background-color",
                                  "lightgreen");
        });
    </script>
</head>
  
<body>
  
    <h1>Welcome to neveropen !!!</h1>
    <div style="border: 1px solid green;">
        <p>This is the first statement.</p>
    </div>
    <br>
  
    <div style="border: 1px solid green;">
        <p>This is the second statement.</p>
    </div>
    <br>
  
    <div style="border: 1px solid green;">
        <p>This is the third statement.</p>
    </div>
    <br>
</body>
  
</html>


In the above code, the background-color of the first “div” element get changed. 
Output: 
 

Here, you can also choose by selecting “id” or “class” of the selected element. 
Code #2: 
 

html




<html>
  
<head>
                 jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $(".main").first().css("background-color",
                                     "lightgreen");
        });
    </script>
</head>
  
<body>
  
    <h1>Welcome to neveropen !!!</h1>
    <div style="border: 1px solid green;">
        <p>This is the first statement.</p>
    </div>
    <br>
  
    <div class="main" style="border: 1px solid green;">
        <p>This is second statement.</p>
    </div>
    <br>
  
    <div class="main" style="border: 1px solid green;">
        <p>This is the third statement.</p>
    </div>
    <br>
</body>
  
</html>


In the above code the elements with first “main” class get highlighted. 
Output: 
 

 

RELATED ARTICLES

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6776 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6904 POSTS0 COMMENTS
Ted Musemwa
7160 POSTS0 COMMENTS
Thapelo Manthata
6859 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS