How to get number of elements in a div using jQuery
source link: https://www.laravelcode.com/post/how-to-get-number-of-elements-in-a-div-using-jquery
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to get number of elements in a div using jQuery
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>
Author : Harsukh Makwana
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]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK