How can I truncate all words greater than 30 characters when page loads?

How can I truncate all words greater than 30 characters using a class name when the page loads?

Been trying to do this for about 5 hours. Trying to conside the following:

  • Truncate long words and churn anything above the minimum length with an ellipse.
  • Only truncate words and not the whole sentence or paragraph.
  • Should truncate text that are inside HTML tags and not truncate the tags themselves.
  • When you hover over the ellipse, it will show you the complete word.
  • The long words are already truncated when the page load (SEO friendly).
  • Block of text are included in a max of 25 <div> elements and a minimum of 1. That’s why I’m not using ID.

So far I have this lines of code:

<script charset="utf-8" language="javascript" type="text/javascript">
function test(gaz) {
		var sbText = gaz.innerHTML;
		var sbTextArr = sbText.split(' ');
		var tempText = "";
		for (var s=0; s<sbTextArr.length; s++) {
			if (sbTextArr[s].length > 30) { sbTextArr[s] = "marco"; }
			gaz.innerHTML = "";
			tempText = tempText + " " + sbTextArr[s];
			gaz.innerHTML = tempText;

<div class="myClass" onmouseover="test(this);"><p>This is a <strong>looooooooooooooo</strong><em>ooooooooooooooooooooooooooooooong</em> word.</p></div>
<div class="myClass" onmouseover="test(this);">A text without long word.</div>
<div class="anotherClass"><p>Another set</p><p>But should not affect if there's a loooooooooooooooooong word.</p></div>

I got this from the web and modified it but not working as I intended it to be.

Useful for posts in forums, blog comments, and guestbooks.


Some jquery ellipsis plugins:

If you don’t want to use jquery then check this out: