For the first forty words and links to continue reading, I suggest:
var s = jQuery(this).text(), fortyWords = s.split(' ').slice(0,39).join(' '), link = document.createElement('a'), linkText = document.createTextNode('continue reading'); link.href = 'http://path.to.article/'; link.appendChild(linkText); $(this).text(fortyWords).append(link);
JS Fiddle proof of concept .
Edited in response to additional questions from OP (in the comments below):
1: Is there a way in Firebug to note the effectiveness of one method against another? IOW: your example looks good, but can I compare its memory and speed against my loop?
Honestly, I don’t know, I'm afraid I don’t use Firefox at all, and although I use Chromium almost exclusively, I haven’t worked with it long enough to detect profiling tools for memory usage or speed.
However, there is JS Perf that allows you to run tests to show the speed of specific approaches; although it does not affect memory usage at all.
2: My version uses the .html()
method and the .outerHTML
property. I continue to see messages on the Internet that they are not reliable. Is this something from IE6? My users are all pretty current, so I wonder why you decided to use .text()
and then add node?
html()
is a good approach to use, but ideally for use only if you want to work with html in a string format; in the above example, it was easier to work with strings, since all I really wanted to work with was a text string. If the element contained other elements that I manipulated with text()
, then I had to use html()
, otherwise these elements would be rewritten when writing / replacing text in the DOM.
I seem to remember that I did not have much success using outerHTML
historically and, frankly, empirically. Therefore, I rarely think to use it, although this is just a matter of personal preference. As for being a hold on IE 6? I'm not sure; I won’t be surprised, but I don’t know at all, unfortunately.
I decided to use text()
because I, as already noted, worked with text; and then I added node, separately, in html()
, because I inserted html node. If I used the same content completely with html()
, then this, I think, worked. But, again, only personal preference and, I think, it makes it clear that I manipulate / work with text or html.
Literature:
- JQuery:
- "Normal" non-JavaScript library: