Web DevCenter
oreilly.comSafari Books Online.Conferences.
MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA

Sponsored Developer Resources

Web Columns
Adobe GoLive
Essential JavaScript
Megnut

Web Topics
All Articles
Browsers
ColdFusion
CSS
Database
Flash
Graphics
HTML/XHTML/DHTML
Scripting Languages
Tools
Weblogs

Atom 1.0 Feed RSS 1.0 Feed RSS 2.0 Feed

Learning Lab






O'Reilly Network Script Library -- Javascript

Word Counter

Language: JavaScript

Download the files for this script (zip format)

With this small function you can calculate the number of words in an HTML document or inside specified elements and include it into your document dynamically.

This function only uses the standardized DOM methods and does not take advantage of any proprietary techniques.

Supported platforms are Mozilla, Netscape 6 and Internet Explorer 5.x.

Instructions

In the zip file you'll find a single file, countwords.js, which has to be pasted or included into your document:

<script src="countwords.js" type="text/javascript"></script>

After including the script you have to choose what to count. You can count the words of a whole document or just an element (and its descendants). If you choose an element, you have to give its own ID, so that the function can access it:

<p id="para1">My first paragraph...</div>

The last step is to call showWords() with the correct arguments after the document has loaded. The first argument is the ID of the element, where the number will be printed, the second one is the ID of the counted element. If omitted, the complete document's text content is counted:

<body onload="showWords('counter1', 'para1')">

You're free to do this as often as desired.

See Document Mathematics: Count Your Words for more details.