Search

How to get number of elements in a div using jQuery

post-title

Use the jQuery .length property

You can simply use the jQuery .length property to find the number of elements in a DIV element or any other element. The following example will alert the number of paragraphs in a <div> element having the class .content on document ready event.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Number of Paragraphs in a Div</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        var matched = $(".content p");
        alert("Number of paragraphs in content div = " + matched.length);
    });
</script>  
</head> 
<body>
    <div class="content">
        <h1>This is a heading</h1>
        <p>This is a paragraph.</p>
        <p>This is another paragraph.</p>
        <div>This is just a block of text.</div>
        <p>This is one more paragraph.</p>
    </div>
</body>
</html>

However, if you want get the numbers of all child elements regardless of their types, just use the universal selector i.e. an asterisk symbol (*), like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Number of Child Elements in a Div</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        var matched = $(".content *");
        alert("Number of elements in content div = " + matched.length);
    });
</script>  
</head> 
<body>
    <div class="content">
        <h1>This is a heading</h1>
        <p>This is a paragraph.</p>
        <div>This is just a <em>block of text</em>.</div>
        <ul>
            <li>An item of an unordered list</li>
            <li>Another item of an unordered list</li>
        </ul>
    </div>
</body>
</html>