2016-11-20 79 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