×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery count child elements

In this tutorial, let's discuss how to count the child elements of an HTML tag using jQuery?
Submitted by Pratishtha Saxena, on July 24, 2022

jQuery :empty Selector

To count child elements using jQuery, there are two different ways:

  1. Using length Property
  2. Using children() Method

1) Count child elements using length property

It is an inbuilt jQuery property that returns the number of elements in a particular HTML element. It helps to count the element within an element.

Syntax:

$(selector).length;

Here, the number of elements, or we can say the length of the selector is returned. Let's see an example of this.

Example 1:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <h2>My List</h2>
    <div id="myList">
      <h3>Continents</h3>
      <ul>
        <li>Asia</li>
        <li>Europe</li>
        <li>North America</li>
        <li>South America</li>
        <li>Africa</li>
        <li>Australia</li>
        <li>Antarctica</li>
      </ul>
    </div>
  </body>
</html>

jQuery:

var count = $("#myList li").length;
console.log(count);

Output:

Example 1: jQuery count child elements


2) Count child elements using children() method

As the name suggests, this method returns all the child elements of an HTML element. Since this will return the child tags, therefore length property can be applied further to just get the length, i.e., count of the child elements.

Syntax:

This way only the count of the child elements will be returned. Let's see an example of this.

Example 2:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <h2>My List</h2>
    <div id="myList">
      <h3>Continents</h3>
      <ul>
        <li>Asia</li>
        <li>Europe</li>
        <li>North America</li>
        <li>South America</li>
        <li>Africa</li>
        <li>Australia</li>
        <li>Antarctica</li>
      </ul>
    </div>
  </body>
</html>

jQuery:

var count = $("#myList ul").children().length;
console.log(count);

Output:

Example 2: jQuery count child elements





Comments and Discussions!

Load comments ↻





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