:lt() Selector


lt selectorversion deprecated: 3.4

Description: Select all elements at an index less than index within the matched set.

  • version added: 1.0jQuery( ":lt(index)" )

    index: Zero-based index.

  • version added: 1.8jQuery( ":lt(-index)" )

    indexFromEnd: Zero-based index, counting backwards from the last element.

As of jQuery 3.4, the :lt pseudo-class is deprecated. Remove it from your selectors and filter the results later using .slice(). For example, :lt(3) can be replaced with a call to .slice( 0, 3 ).

index-related selectors

The index-related selectors (including this "less than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $( ".myclass:lt(1)" ) selects the first element in the document with the class myclass, rather than selecting no elements. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

Prior to jQuery 1.8, the :lt(index) selector did not accept a negative value for index

Additional Notes:

  • Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

Example:

Give TDs less than the one with the 4th index (TD#4) a yellow background and TDs less than the one with -2nd index a red text color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>lt demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
<script>
$( "td:lt(4)" ).css( "backgroundColor", "yellow" );
$( "td:lt(-2)" ).css( "color", "red" );
</script>
</body>
</html>

Demo: