• jQuery Video Tutorials

jQuery :gt() Selector



The :gt() selector in jQuery is used to select elements that have an index greater than the specified index. The index is zero-based, meaning the first element has an index of 0.

Syntax

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

$(":gt(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 greater than this value will be selected.

Example 1

In the following example, we are using the jQuery :gt() Selector to select the list elements with an index greater than 1 −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li:gt(1)").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 third (index: 2) and fourth (index: 3) 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 greater 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:gt(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 greater than 2 will be hidden.

Example 3

Here, we are selecting the paragraph elements with an index greater than 0 −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:gt(0)").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 beyond will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements