Character count within separate paragraphs (jQuery)

Asked

Viewed 102 times

2

How to use jQuery to sum characters in different paragraphs? Example:

<div id="test">
    <p>Lorem Ipsum</p>
    <p>Lorem Ipsum</p>
</div>

Note. Cannot add id and class in the tags <p>.

I managed to do a function (here), but she uses the .each() jQuery. I wonder if there is any other more efficient way to solve this.

1 answer

3


You can do this with native Javascript using a loop for and .getElementsByTagName():

var count = 0;
var ps = document.getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) {
    var text = ps[i].textContent || ps[i].innerText;
    count += text.length;
}
alert("count: " + count)

jsFiddle: https://jsfiddle.net/eet9yp4q/

If you put that at the end of body will go well without needing a role to involve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.