Cover Image for jQuery first() method
91 views

jQuery first() method

The jQuery first() method is used to select the first element from a matched set of elements. It returns a new jQuery object containing only the first element that matches the selector or filter criteria.

Here’s the basic syntax of the first() method:

$(selector).first()

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery first() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>

    <script>
        $(document).ready(function() {
            // Select the first list item in the unordered list
            var firstItem = $("ul li").first();

            // Add a class to the first list item
            firstItem.addClass("highlight");
        });
    </script>
</body>
</html>

In this example, we have an unordered list with three list items. We use the first() method to select the first list item, and then we add a class “highlight” to it. As a result, only the first list item will have the “highlight” class applied to it.

The first() method is useful when you want to target the first element in a collection or when you want to perform specific operations on the first element among a set of matched elements. It can help you access and manipulate elements with ease and precision.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS