• jQuery Video Tutorials

jQuery :lt() Selector



The :lt() selector in jQuery is used to select elements with an index less than a specified index within a matched set. This selector starts counting from zero (0) for the first element in the set and so on.

Syntax

Following is the syntax of jQuery :lt() Selector −

$(":lt(index)")

Parameters

Here is the description of the above syntax −

  • index: A zero-based integer indicating the index to compare against. Elements with an index lesser than this value will be selected.

Example 1

In the following example, we are using the jQuery :lt() Selector to select the list elements with an index lesser than 2 −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li:lt(2)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ul>
</body>
</html>

After executing the above program, the first (index: 0) and second (index: 1) list items will be highlighted with yellow background color.

Example 2

In this example, we are selecting and hiding the table rows with an index lesser than 2 −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("tr:lt(2)").hide();
        });
    </script>
</head>
<body>
    <table border="1">
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
        <tr><td>Row 4</td></tr>
        <tr><td>Row 5</td></tr>
    </table>
</body>
</html>

After executing, the table rows that has index lesser than 2 will be hidden.

Example 3

Here, we are selecting the paragraph elements with an index lesser than 2 −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:lt(2)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
</body>
</html>

The second paragraph and above will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements