简体   繁体   English

如何使用 JavaScript 计算 div class 的出现次数,并在没有 jQuery 的情况下将数字打印到屏幕上?

[英]How can I use JavaScript to count the number of occurrences of a div class, and print the number to screen without jQuery?

I have a page that contains many div elements with the same class.我有一个页面,其中包含许多具有相同 class 的 div 元素。 All I want is a bit of JS to count them and print the total to the screen.我想要的只是一点 JS 来计算它们并将总数打印到屏幕上。

Try this尝试这个

 const divs = document.querySelectorAll('div') console.log(divs.length)
 <div>item 1</div> <div>item 2</div> <div>item 3</div>

See

 document.getElementById("result").innerHTML = "Count: " + document.querySelectorAll('.test').length;
 <div id="result"></div> <div class="test">Coffee</div> <div class="test">Milk</div> <div class="test">Soda</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM