I’m wondering if there’s a way to count the words inside a div for example. Say we have a div like so:
<div id='content'> hello how are you? </div>
Then have the JS function return an integer of 4.
Is this possible? I have done this with form elements but can’t seem to do it for non-form ones.
Any ideas?
g
If you know that the DIV is only going to have text in it, you can KISS:
If the div can have HTML tags in it, you’re going to have to traverse its children looking for text nodes:
This is the same logic that the jQuery library uses to achieve the effect of its
text()function. jQuery is a pretty awesome library that in this case is not necessary. However, if you find yourself doing a lot of DOM manipulation or AJAX then you might want to check it out.EDIT:
As noted by Gumbo in the comments, the way we are splitting the strings above would count two consecutive spaces as a word. If you expect that sort of thing (and even if you don’t) it’s probably best to avoid it by splitting on a regular expression instead of on a simple space character. Keeping that in mind, instead of doing the above split, you should do something like this:
The only difference being on what we’re passing to the split function.