Q:

How to get number of elements in a div using jQuery

0

How to get number of elements in a div using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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-3.5.1.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-3.5.1.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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to replace all occurrences of a string in Java... >>
<< How to display all items or values in an array usi...