admin管理员组文章数量:1432187
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>
本文标签: htmlhow to count words in p tag in javascriptStack Overflow
版权声明:本文标题:html - how to count words in p tag in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745582710a2664714.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论