I have a large block of HTML. I won't get into unnecessary specifics, but let's just say that it's not possible for me to edit this HTML directly or on the server side. Any changes I make to it has to be on the client side, through JavaScript magic of some sort. What I want to do is grab any words in this block that are over a certain length and truncate them, maybe slap a "..." at the end. I've tried many techniques, but I just haven't been able to do it. Here's the closest I've gotten:
Expand|Select|Wrap|Line Numbers
- var sbText = document.getElementById('searchbody').innerHTML;
- var sbTextArr = sbText.split(' ');
- for (var s=0; s<sbTextArr.length; s++) {
- document.getElementById('searchbody').innerHTML = '';
- var tempText = document.createTextNode(sbTextArr[s] + ' ');
- document.getElementById('searchbody').appendChild(tempText);
- if (sbTextArr[s].length > 30) { sbTextArr[s] = 'chicken'; }
- }
I know innerHTML is proprietary, but it works and all I'm using it for here is to read the HTML and then zero it out, so I figured it was OK.
Anyway, as you can see, what I'm trying to do here is read the contents of a div called "searchbody," put those contents into a variable, create an array with each word in that variable as an element by splitting the variable at each space, replace each array element greater than 30 characters with the word "chicken," and appending all the resulting elements to the end of the searchbody div. This almost works, but the problem is that the HTML doesn't render as HTML, it renders as text. An image tag won't show up as an image -- it shows up as an image tag.
Does anyone know any way to circumvent this problem? Or, alternatively, an entirely different approach?
Thanks a lot!