Get the second child using jQuery

In this tutorial, we'll specifically learn how to get the second child of the selected element using jQuery?
Submitted by Pratishtha Saxena, on June 26, 2022

jQuery is a JavaScript library used to simplify HTML DOM tree traversal and manipulation, and event handling. It is free, open-source software. It is user-friendly and easy to use.

Note: Always remember to apply the CDN link while working with jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

To get the second child specifically, here two methods are going to be discussed.

  1. Using :nth-child() Selector
  2. Using eq() Method

1) Using :nth-child() Selector

As the name suggests, nth-child() selector helps in selecting the specified, nth, number of child irrespective of the parent. It is an inbuilt selector of jQuery. The number of the child has to be defined within the brackets. 

Syntax:

:nth-child(n);

Let's take a simple example of this for better understanding,

Example 1:

HTML:

<!doctype html>

<html lang="en">
   <head>
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   </head>
   <body>
      <h3>Second Child</h3>
      <table class="myTable" cellpadding="10px">
         <th>India</th>
         <th>Australia</th>
         <th>Russia</th>
         <th>Canada</th>
         <th>USA</th>
      </table>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
        $( "table.myTable th:nth-child(2)" ).css( "color", "blue" );
    });
</script>

Output:

Example 1: Get the second child

2) Using eq() Method

The eq() method in jQuery helps to find and return the element value at the specified index. The index is given within the brackets. The index here starts from 0, which means 0 here is the first number of child and 1 is the second number of children.

Syntax:

$(selector).eq(index);

Let's understand this better with an example.

Example 2:

HTML:

<!doctype html>

<html lang="en">
   <head>
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   </head>
   <body>
      <h3>Second Child</h3>
      <ol class="myList">
         <li>1st Position item</li>
         <li>2nd Position item</li>
         <li>3rd Position item</li>
         <li>4th Position item</li>
      </ol>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
        $( "li").eq(1).css( "color", "red" );
    });
</script>

Output:

Example 2: Get the second child





Comments and Discussions!

Load comments ↻





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