jQuery first() with Example

jQueryWeb DevelopmentFront End Technology

The first() method in jQuery selects the first element from the specified elements.

Syntax

The syntax is as follows −

$(selector).first()

Example

Let us now see an example to implement the jQuery first() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("p").first().css("color", "blue");
   });
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is a line. </p>
<p>This is another line.</p>
<p>This is line 3.</p>
</body>
</html>

Output

This will produce the following output −

Example

Let us see another example −

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      background-color: orange;
      border: 2px dashed red;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("p").first().addClass("one");
   });
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is a line. </p>
<p>This is another line.</p>
<p>This is line 3.</p>
<p>This is line 4.</p>
<p>This is line 5.</p>
</body>
</html>

Output

This will produce the following output −

raja
Published on 12-Nov-2019 12:00:45
Advertisements