• jQuery Video Tutorials

jQuery :first-of-type Selector



The :first-of-type Selector in jQuery is used to select the first element of its type (e.g., <p>, <div>, etc.) within its parent. This selector is useful for styling or manipulating the first occurrence of a specific type of element within its parent.

Syntax

Following is the syntax of jQuery :first-of-type Selector −

$(" :first-of-type");

Parameters

Here is the description of the above syntax −

  • :first-of-type − Selects the first element of its type within the parent.

Example 1

In the following example, we are using the jQuery :first-of-type Selector to select the first <p> element within the <div> −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Change the color of the first <p> element within the <div>
            $("div p:first-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>
        <p>First paragraph in div.</p>
        <p>Second paragraph in div.</p>
    </div>
</body>
</html>

After executing the above program, the selected element will be highlighted with yellow background color.

Example 2

In this example, we are selecting the first <li> element within the <ul> −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Highlight the first <li> element within the <ul>
            $("ul li:first-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>First item in list</li>
        <li>Second item in list</li>
        <li>Third item in list</li>
    </ul>
</body>
</html>

After executing, the selected <li> items will be highlighted with yellow background.

Example 3

Here, we are selecting the first <h1> element within the <section> −

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First Heading in section</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Change the font size of the first <h1> element within the <section>
            $("section h1:first-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <section>
        <h1>First heading in section</h1>
        <h1>Second heading in section</h1>
    </section>
</body>
</html>

The first <h1> element within the <section> will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements