jQuery Tip: How to Count Child Elements With jQuery

In this article, we are sharing a simple tip to count child elements of an element with jQuery. We’ll use two strategies for counting child elements of an element. These are:

 

  • .length – is used to get the number of elements in the jQuery object.
  • .children() – is used to get the children of each element in the set of matched elements.

HTML Code

Following is a sample HTML code for testing.
[code type=”php”]

  • one
  • two
  • three
  • four
  • five
  • six

[/code]

jQuery Code: First Strategy

[code type=”php”]
var count = $(“#parent li”).length;
alert(count);
[/code]

jQuery Code: Second Strategy

[code type=”php”]
var count2 = $(“#parent ul”).children().length;
alert(count2);
[/code]

I hope, you’ll find these code snippets understandable.

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment