.length
propertyYou 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>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to remove wrapper element but keep the text content intact using jQuery
Use the jQuery unwrap() method...Laravel 8 Sanctum API Authentication Tutorial
In this example, you will learn laravel...Django 3 Multiple File-Image Upload with Angular 9
In the precedent tutorial we have optica...Laravel 5.5 - simple crud operation with example
Today, we are sharing how to make s...How to use the PHP Ternary Operator
If else condition is used to execute the...