×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery :first-child Selector

jQuery | :first-child Selector: Learn about the jQuery :first-child Selector with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on November 04, 2022

:first-child Selector

The jQuery :first-child selector helps to select the very first child occurrence of the specified tag in their parent elements. It is used along with some tag names prepended to it. It will return the first child of the parent element if the first child is of the specified tag.

It is important to know that, this will return only those first-child div (here), where the very first child of the parent element is the specified tag (say div). If the parent element has some other tag as its first child, say – span, and the second first child as div, then :first-child selector will not consider the second first div as the first child. This is possible by using :first-of-type selector.

:first-child Selector Syntax

$('elementName:first-child');

Once the elements are selected, you can access them and perform the actions that you want to perform on them. The example given below shows the selection of the first child element of the 'p' tag on click by passing the appropriate selector.

jQuery :first-child Selector Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      div{
      color: darkblue;
      font-size: large;
      font-weight: bold;
      }
      p{
      color: darkgreen;
      font-size: medium;
      font-weight: bold;
      }
    </style>
  </head>
  
  <body>
    <h2>jQuery - First Child Selector</h2>
    <p>Click the button and get the first child of the selected element.</p>
    <button>First Child Selector</button>
    <hr>
    <div>
      Welcome to Include Help !
      <p>This is a jQuery Tutorial for Selectors.</p>
      <p>Here we are discussing the :first-child Selector.</p>
    </div>
    <div>Thanks for visiting !</div>
    <hr>
    <h4>First Child is given below:</h4>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('p:first-child').css('color','red').appendTo('h4');
        });
    });
  </script>
</html>

Output:

Example 1: jQuery :first-child Selector


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.