I want to count words in few paragraphs in javascript. How i call to my javascript function?
<html>
<head></head>
<script type="text/javascript">
function cnt() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++) {
alert(paragraphs[i].innerHTML);
}
}
</script>
<body>
<p>some text</p>
<p>some text</p>
<p>text text text</p>
</html>
I want to count words in few paragraphs in javascript. How i call to my javascript function?
<html>
<head></head>
<script type="text/javascript">
function cnt() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++) {
alert(paragraphs[i].innerHTML);
}
}
</script>
<body>
<p>some text</p>
<p>some text</p>
<p>text text text</p>
</html>
Share
Improve this question
edited Jan 30, 2015 at 19:30
talemyn
7,9804 gold badges33 silver badges52 bronze badges
asked Jan 30, 2015 at 19:20
tokenaizertokenaizer
2081 gold badge5 silver badges18 bronze badges
3
- 4 Split them on the spaces and count the length? – j08691 Commented Jan 30, 2015 at 19:21
-
5
.innerHTML
is going to fetch any html inside the tags as well. you probably want.innerText
, which would fetch ONLY the visible/readable text and ignore tags. – Marc B Commented Jan 30, 2015 at 19:23 - Define “word”. Is “tax-free” one word or two? How about “日本国”? – Jukka K. Korpela Commented Jan 30, 2015 at 20:13
2 Answers
Reset to default 2Split on spacing, and use the resulting array's length
:
function wordCount(elements) {
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(/\s/).length;
}
return count;
}
var wordsInParagraphs = wordCount(document.getElementsByTagName("p"));
You could try something like this:
function cnt(){
var paragraphs = document.getElementsByTagName("p");
var count = 0;
for(var i = 0; i < paragraphs.length; i++)
{
count += paragraphs[i].innerHTML.split(' ').length;
}
}
Please try the following snippet:
// I changed the name of function, in order to be more meaningfull.
function countWords(){
// Select all the p elements in the page.
var paragraphs = document.getElementsByTagName("p");
// The counter.
var count = 0;
for(var i = 0; i < paragraphs.length; i++)
{
// Split the innerHtml of the current paragraph to count the words.
count += paragraphs[i].innerHTML.split(' ').length;
}
document.write("Number of words: "+count);
}
countWords();
<p>some text</p>
<p>some text</p>
<p>text text text</p>