Character count inside distinct paragraphs (jQuery)

2

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

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

Obs. Can not add id and class to <p> tags.

I was able to do a function ( here ), but it uses .each() of jQuery. I would like to know if there is any other more efficient way to resolve this.

    
asked by anonymous 09.04.2015 / 16:28

1 answer

3

You can do this with native JavaScript using a for loop 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: link

If you put this at the end of body it will run fine without needing a function to wrap.

    
09.04.2015 / 16:35