jQuery first() Method (original) (raw)

Last Updated : 30 Sep, 2024

The jQuery first() method selects and returns the first element from a set of matched elements. It's commonly used to manipulate or retrieve the first element within a group, ensuring that operations only apply to the first match.

**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.

**Example: In this example, the first() method is used to select the first

element on the page. It applies a light green background color specifically to that first selected
.

html `

<h1>Welcome to GeeksforGeeks !!!</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>

`

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

**Example: In this example we use jQuery's first() method to target the first

with the class "main" and changes its background color to light green when the page finishes loading.

html `

<h1>Welcome to GeeksforGeeks !!!</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>

`

In the above code the elements with first "main" class get highlighted.
**Output: