jQuery

How to Get Number of Elements inside a DIV with jQuery

In this tutorial, we are going to see how to get Number of elements inside a DIV with jQuery. You can use jQuery’s .length property to find the number of elements in a DIV or any other element. The following example will display the number of paragraphs in a DIV with the class “.example”.
 

How to Get Number of Elements inside a DIV with jQuery
$(document).ready(function() {
    var paragraphs = $(".example p");
    alert("Number of paragraphs inside DIV is " + paragraphs.length);
});
<div class="example">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
    <p>Paragraph 5</p>
</div>

Output:

Number of paragraphs inside DIV is  5

However, if you want to know the number of child elements regardless of their type, just use the universal selector (*), like this:

$(document).ready(function() {
    var elements = $(".example *");
    alert("Number of paragraphs inside DIV is " + elements.length);
});
<div class="example">
    <span>lorem ipsum</span>
    <p>Paragraph</p>
    <h1>Title</h1>
</div>

Output:

Number of paragraphs inside DIV is 3
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *