cmp cmp - 13 days ago 6
Javascript Question

Javascript count DIVS and display result

I'm looking to count a set of DIVS and return its number.

I have:

<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>


Is there a way in Javascript I can count how many times the newsTitle DIV appears and document.write a count, like:

document.write("There is a total of " + newsCountTotal "News stories")


Can I do something like:

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


(I hope you understand my logic).

Length is used to count, right? but how do I impliment what I'm after exactly? Do I need a For Loop to keep checking how many I have as well as .length ?

Thanks :-)

Answer

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>

Comments