2016-11-20 47 views
0

我正在计算一组DIVS并返回它的编号。Javascript count DIVS and display result

我:

<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("There is a total of " + newsCountTotal "News stories") 

我能做些什么像:

var newsCountTotal; 
newsCountTotal = document.getElementByClassName("newsStories").length 

(我希望你能理解我的逻辑)。

长度用于计数,对吧?但是,我究竟会如何侮辱我?我是否需要For循环来检查我有多少以及.length?

感谢:-)

+1

通常,您不会使用文件撰写。相反,您会定位另一个元素,并将该值设置为值或innerHTML。 – Taplar

+0

'.newsTitle h1'? – Mahi

+0

@Mahi呢? – cmp

回答

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>

+0

非常感谢@Taplar。干杯。 – cmp