[英]How can i count the total number of instances of a specific data attribute in my html?
For example, for the following HTML, the answer would be 4. As there are 4 instances of data-example
例如,对于下面的 HTML,答案是 4。因为有 4 个
data-example
<h1>Random text</h1>
<div data-example>
<img src="eg.png">
</div>
<p>More random text</p>
<ul>
<li data-example>eg1</li>
<li data-example>eg2</li>
<li data-example>eg3</li>
</ul>
Ideally, I was hoping for an inbuilt function like "get_total_instances", but i haven't found anything like this.理想情况下,我希望有一个像“get_total_instances”这样的内置 function,但我还没有找到这样的东西。
$('[data-example]').get_total_instances(); // output should be 4
or或者
get_total_instances('[data-example]'); // output should be 4
It's the length
property of the jQuery object:这是 jQuery object 的
length
属性:
$("[data-example]").length
It tells you how many elements are in the set that you selected.它告诉您选择的集合中有多少元素。
Live Example:现场示例:
console.log($("[data-example]").length);
<h1>Random text</h1> <div data-example> <img src="eg.png"> </div> <p>More random text</p> <ul> <li data-example>eg1</li> <li data-example>eg2</li> <li data-example>eg3</li> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
And for those who are not using jQuery, here's the vanilla JavaScript equivalent:对于那些不使用 jQuery 的人,这里是等效的香草 JavaScript:
document.querySelectorAll("[data-example]").length;
console.log(document.querySelectorAll("[data-example]").length);
<h1>Random text</h1> <div data-example> <img src="eg.png"> </div> <p>More random text</p> <ul> <li data-example>eg1</li> <li data-example>eg2</li> <li data-example>eg3</li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.