I'm trying to add a "Read more" link when HTML text exceeds about 50 characters and after the last closing tag.
$(document).ready(function(){
var maxLength = 50;
$(".html-text").each(function(){
var myStr = $(this).html();
if($.trim(myStr).length > maxLength){
var newStr = myStr.substring(0, maxLength);
var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
$(this).empty().html(newStr);
$(this).append('<a href="javascript:void(0);" class="read-more">Read more</a>');
$(this).append('<span class="more-text">' + removedStr + '</span>');
}
});
$(".read-more").click(function(){
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="html-text">
<p>John has a red and white car that goes really fast.</p> <p>He needs to be careful.</p>
</div>
My result:
<div class="html-text">
<p>John has a red and white car that goes really fas <a href="javascript:void(0);" class="read-more">Read more</a>
</div>
Expected result:
<div class="html-text">
<p>John has a red and white car that goes really fast.</p> <a href="javascript:void(0);" class="read-more">Read more</a>
</div>
Any idea? Hope I made myself clear.
etc...
– Rubyx Feb 03 '20 at 21:55