jQuery eq() first() last()

When jQuery selects multiple elements, you often need to work with just one of them — the first, the last, or a specific one by position. The first(), last(), and eq() methods let you pinpoint exactly which element from a matched set you want.

first() — Select the First Element

The first() method returns only the first element from a matched set.

$("p").first().css("font-weight", "bold");
// Only the first <p> on the page gets bold text

$("li").first().addClass("top-item");
// Only the first list item gets the class

last() — Select the Last Element

The last() method returns only the last element from a matched set.

$("p").last().css("color", "grey");
// Only the last <p> gets grey text

$("tr").last().addClass("total-row");
// The last table row (likely a totals row) gets a class

eq(n) — Select by Index

The eq(n) method returns the element at a specific index. Index starts at 0 for the first element. Negative values count from the end.

$("li").eq(0)   // first item  (same as first())
$("li").eq(1)   // second item
$("li").eq(2)   // third item
$("li").eq(-1)  // last item   (same as last())
$("li").eq(-2)  // second-to-last item

Diagram: Index Positions

  $("li") matches:
  ┌───────────────────────────────────────────┐
  │ Index  0  (or -4) → Apple       ← first() │
  │ Index  1  (or -3) → Banana                │
  │ Index  2  (or -2) → Cherry                │
  │ Index  3  (or -1) → Dates       ← last()  │
  └───────────────────────────────────────────┘

  eq(1)  → Banana
  eq(-2) → Cherry

first() vs :first Filter Selector

$("p").first()        → preferred method form
$("p:first")          → filter selector form (same result)

Both are equivalent. The method form is recommended for better performance.

Practical: Style Specific Table Rows

$(document).ready(function() {
    // Header row — bold
    $("tr").first().css("font-weight", "bold");

    // Footer/total row — different background
    $("tr").last().css("background", "#e8f5e9");

    // Third row — highlight something specific
    $("tr").eq(2).css("background", "#fff3e0");
});

Practical: Image Gallery Navigation

HTML:
<div id="gallery">
    <img src="img1.jpg" class="slide" />
    <img src="img2.jpg" class="slide" />
    <img src="img3.jpg" class="slide" />
</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>

jQuery:
$(document).ready(function() {
    var current = 0;
    var total = $(".slide").length;

    function showSlide(index) {
        $(".slide").hide();
        $(".slide").eq(index).show();
    }

    showSlide(current);

    $("#nextBtn").click(function() {
        current = (current + 1) % total;
        showSlide(current);
    });

    $("#prevBtn").click(function() {
        current = (current - 1 + total) % total;
        showSlide(current);
    });
});

Diagram: Slideshow with eq()

  Slides: [img1] [img2] [img3]
  current = 0 → .eq(0) visible = img1

  User clicks Next:
  current = 1 → .eq(1) visible = img2

  User clicks Next again:
  current = 2 → .eq(2) visible = img3

  User clicks Next again:
  current = 0 → .eq(0) visible = img1  (wraps around)

Chaining After first(), last(), eq()

All three methods return a jQuery object, so you can chain any jQuery method after them.

$("ul").first().find("li").last().css("color", "red");
// In the first <ul>, find the last <li> and make it red

$(".card").eq(1).find("button").prop("disabled", true);
// In the second card, disable the button

Comparison: first(), last(), eq()

MethodReturnsIndex needed?
first()First elementNo
last()Last elementNo
eq(n)Element at index nYes

Quick Summary

  • first() selects the first element from a matched set.
  • last() selects the last element from a matched set.
  • eq(n) selects the element at index n (zero-based).
  • Negative indices in eq() count from the end: eq(-1) is the last element.
  • All three return a jQuery object that supports full method chaining.

Practical: Alternating Row Colors Without CSS

When CSS classes are not available, use eq() and each() together to apply alternating styles in JavaScript.

$("tr").each(function(index) {
    if (index % 2 === 0) {
        $(this).css("background", "#f9f9f9");
    } else {
        $(this).css("background", "#ffffff");
    }
});
// .eq(0), .eq(2), .eq(4) get the light grey background.

Leave a Comment

Your email address will not be published. Required fields are marked *