With the jQuery first() method, we can get the first element or div in a series of elements or divs.

$("div").first();

Let’s say we have the following HTML:

This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

As we can see, we have three divs with class “divs”, each of which has two paragraphs. If we want to get the first div with class “divs” and change only its background color, we can do this using the jQuery first() method.

Here is the JavaScript code that would accomplish this:

$(".divs").first().css("background","green");

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery(".divs").first().css("background","green");

Using jQuery to Get the First Div and Change its Background

In this example, we will get the first div of a series of divs with the same class using the jQuery first() method, and change its background color.

Here is our HTML setup with some styles added to the divs:


This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

Change background

We can utilize the jQuery first() method, and the jQuery css() method to change the background of the first div.

Below is the Javascript code which will allow the user to be able to change the first div’s background color using jQuery.

$("#click-me").click(function(){
  $(".divs").first().css("background","#c1e9c1");
});

The final code and output for this example is below:

Code Output:

This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

Change background

Full Code:


This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

Change background
<script> $("#click-me").click(function(){ $(".divs").first().css("background","#c1e9c1"); }); </script>

Hopefully this article has been useful to help you understand the jQuery first() method.

Categorized in:

jQuery,

Last Update: February 26, 2024