jQuery Traversing - first() Method

Example

Highlight the first span in the paragraph:

$("p span").first().addClass('highlight');

Try it yourself

Definition and Usage

first() reduces the matched element collection to the first element in the collection.

Syntax

.first()

Detailed Description

If a jQuery object representing a collection of DOM elements is given, the .first() method will construct a new jQuery object using the first matching element.

Think about the following page with a simple list:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the list item collection:

$('li').first().css('background-color', 'red');

Try it yourself

The result of this call is that the first item is set to a red background.