如何在jQuery中计算文档中的每个元素,包括头部主体
在这篇文章中,我们将使用jQuery来计算文档中的每个元素(包括头部、主体等)。为了计算所有的HTML元素,我们使用length属性。length属性是用来计算jQuery对象中的元素数量。
语法:
$(selector).length
其中selector是要计算其长度的对象。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Import jQuery cdn library -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function () {
("button").click(function () {
var count = (".GFG").find("*").length;
("p").after("<h3>Total Div Elements: "
+ count);
});
});
</script>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
How to count all elements
within a div using jQuery?
</h3>
<div class="GFG">
<p>
GeeksforGeeks computer
science portal
</p>
<input type="text">
</div><br>
<button>Click Here!</button>
</body>
</html>
输出:
点击按钮前:
点击按钮后: