How to Select the First Paragraph Using jQuery

Selecting the first paragraph element on a web page using jQuery can be accomplished in several ways depending on your preferred syntax and performance requirements. This guide covers the most common and efficient jQuery methods and selectors to target the initial <p> element, including the .first() traversal method, the :first pseudo-selector, and index-based selection with .eq().

Method 1: Using the .first() Method

The .first() method is the most recommended approach because it provides clear readability and better execution performance compared to custom pseudo-selectors.

// Selects the first <p> element on the page
const $firstParagraph = $('p').first();

// Example: Change its text color to red
$firstParagraph.css('color', 'red');

This method first collects all paragraph elements into a jQuery object and then reduces the set to the very first element found in the DOM.


Method 2: Using the :first Selector

jQuery includes a custom pseudo-class selector, :first, which allows you to target the first matching element directly within the selector string.

// Selects the first <p> element directly
$('p:first').css('color', 'red');

While concise, custom selectors like :first cannot leverage the browser's native querySelectorAll() engine, making them slightly slower than the .first() method on large DOM trees.


Method 3: Using the .eq() Method

If you need zero-based index targeting, the .eq(0) method achieves the same result as .first().

// Selects the element at index 0 (the first one)
$('p').eq(0).css('color', 'red');

Alternatively, the :eq() selector string can be used:

$('p:eq(0)').css('color', 'red');

Like the :first selector, the string-based :eq(0) is slower than the chainable .eq(0) method.


Method 4: Using CSS Standard Selectors (:first-of-type)

If you want your code to use native CSS selectors that match browser specifications, you can combine jQuery with :first-of-type:

// Selects the first paragraph within its parent container
$('p:first-of-type').first().css('color', 'red');

Note that :first-of-type selects the first paragraph relative to each parent container on the page, so appending .first() ensures only the very first one across the entire document is selected.