My apologies if I've framed this question incorrectly or if it's been asked and answered previously, my search turned up similar Q&A's which were based around JQuery and I'm looking for a pure JavaScript solution.
var len = 100;
var p = document.getElementById('shrinkMe');
if (p) {
var trunc = p.innerHTML;
if (trunc.length > len) {
trunc = trunc.substring(0, len);
trunc = trunc.replace(/\w+$/, '');
trunc += '<a href="#" ' +
'onclick="this.parentNode.innerHTML=' +
'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
'Read More<\/a>';
p.innerHTML = trunc;
}
}
The fiddle truncates text with JavaScript, however in it's current state it's for a single occurrence which isn't quite what I need. I have multiple occurrences of 'shrinkMe' as a div id in the body of my html and as .getElementById is used this will need to be tweaked as at the moment when "Read More" is clicked it expands all occurrences simultaneously. I believe that changing to .getElementsByClassName may be the solution to enable me to have multiple occurrences of a class name opposed to being restricted to one instance of .getElementById but I'm unsure quite how to make the switch.
I'm also looking for a clickable "Read Less" to be shown once "Read More" is clicked, with "Read Less" returning the text back to the truncated state, with "Read More" then being visible once again and so on.
In summary I'm asking for assistance to:
- Switch .getElementById to .getElementsByClassName
- Add "Read Less" to show post "Read More" click.
Thanks for taking the time to read this - sorry if I've been unintentionally unclear in anyway. If so please let me know and I'll try to explain further.