How To Filter HTML Elements Using First Method In JQuery

admin_img Posted By Bajarangi soft , Posted On 16-10-2020

In JQuery The most basic filtering methods is first() which allow you to select a specific element based on its position in a group of elements.The first() method returns the first element of the specified elements. So today we discuss In this article about first method

How To Filter HTML Elements Using First Method In JQuery

Step 1:Create index.html file and implement below code.

<p>This is a paragraph.</p>

<div style="border: 1px solid black;">
    <p>A paragraph in a div.</p>
    <p>Another paragraph in a div.</p>
</div>
<br>

<div style="border: 1px solid black;">
    <p>A paragraph in another div.</p>
    <p>Another paragraph in another div.</p>
</div>
<br>

<div style="border: 1px solid black;">
    <p>A paragraph in another div.</p>
    <p>Another paragraph in another div.</p>
</div>


Step 2:Implement jquery to use first methods.

<script>
    $(document).ready(function(){
        $("div").first().css("background-color", "yellow");
    });
</script>


Complete Code For Using First Method In JQuery 
 
<!DOCTYPE html>
<html>
<head>
    <title>How To Filter HTML Elements Using First Method In JQuery</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
        <p>This is a paragraph.</p>

        <div style="border: 1px solid black;">
            <p>A paragraph in a div.</p>
            <p>Another paragraph in a div.</p>
        </div>
        <br>

        <div style="border: 1px solid black;">
            <p>A paragraph in another div.</p>
            <p>Another paragraph in another div.</p>
        </div>
        <br>

        <div style="border: 1px solid black;">
            <p>A paragraph in another div.</p>
            <p>Another paragraph in another div.</p>
        </div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("div").first().css("background-color", "yellow");
    });
</script>

Related Post