我想要计算一组DIVS并返回它的号码。
我有:
<div id="newsArea">
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 1</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 2</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 3</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 4</div>
<!-- etc and so on, depending on however many news stories.. -->
</div>
Javascript中有没有办法我可以计算newsTitle DIV出现的次数和document.write计数,如:
document.write("There is a total of " + newsCountTotal "News stories")
我可以这样做:
var newsCountTotal;
newsCountTotal = document.getElementByClassName("newsStories").length
(我希望你理解我的逻辑)。
长度用于计算,对吗?但是我如何才能完全理解我的意思呢?我是否需要一个For循环来继续检查我有多少以及.length?
谢谢: - )
答案 0 :(得分:0)
var storyCount = document.querySelectorAll('.newsTitle').length
document.querySelector('#storyCount').innerHTML = storyCount;
<div id="newsArea">
<div>(<span id="storyCount"></span>) Articles</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 1</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 2</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 3</div>
<div class="newsTitle"><h1>News Title</h1></div>
<div class="newsContent">News content for post 4</div>
<!-- etc and so on, depending on however many news stories.. -->
</div>