Filter Selectors

Pick elements by position with :first, :last, :even, :odd and more.

Syntax$("li:first"), $("tr:even"), $("p:eq(2)")

Filter selectors start with a colon and narrow a set by position or state.

FilterSelects
:firstthe first matched element
:lastthe last matched element
:eveneven-indexed elements (0, 2, 4…)
:oddodd-indexed elements (1, 3, 5…)
:eq(n)the element at index n
:contains(text)elements containing text

Indexes are zero-based, so :even selects the 1st, 3rd, 5th… rows visually.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A pricing table uses :even and :odd to apply alternating row colours without extra CSS classes.
  • A wizard script uses :first and :last to disable the Previous and Next buttons at the boundary steps.
  • A data feed applies :lt(5) to show only the five most recent entries in a news ticker.

More examples

Alternate row colours with :even/:odd

:even and :odd select alternating rows (0-indexed) to stripe the table without extra classes.

Example · html
<table id="data">
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
  <tr><td>Row 4</td></tr>
</table>
<script>
$(function () {
  $("#data tr:even").css("background", "#f0f4ff");
  $("#data tr:odd").css("background", "#fff");
});
</script>

Target only the first list item

:first and :last select the boundary items of the matched set without needing index arithmetic.

Example · html
<ul id="steps">
  <li>Install</li>
  <li>Configure</li>
  <li>Run</li>
</ul>
<script>
$(function () {
  $("#steps li:first").css("font-weight", "bold");
  $("#steps li:last").css("color", "green");
});
</script>

Show only first five items with :lt

:gt(4) selects every item beyond index 4 (the fifth), hiding everything after the first five entries.

Example · html
<ul id="feed">
  <li>Item 1</li><li>Item 2</li><li>Item 3</li>
  <li>Item 4</li><li>Item 5</li><li>Item 6</li>
</ul>
<script>
$(function () {
  $("#feed li:gt(4)").hide();
});
</script>

Discussion

  • Be the first to comment on this lesson.
Filter Selectors — jQuery | SoundsCode