Timmy Von Heiss Timmy Von Heiss - 3 months ago 12
jQuery Question

using substr to limit characters inside of an element

I am paginating users and in my view I have:

<li class="profile">
<%= user.profile %>
</li>


I want to limit
li.profile
to 200 characters followed by three dots
'...'


Below does not work:

$(document).ready(function(){
$("li.profile").each(function(){
if ($(this).html().length > 200) {
$(this).html($(this).html().substr(0, 200));
$(this).append('...');
}
});
});


from developer tools

this is the way it looks in developer tools.

css

li.profile {
font-size: 14px;
padding-bottom: 5px;
text-align: left;
padding-left: 5px;
}

Answer

Use .text(); .html() sets .innerHTML of element, not .textContent

$(document).ready(function(){
   $("li.profile").each(function(){
       if (this.textContent.length > 200) {
           $(this).text(function(_, text) {
             return text.substr(0, 200).concat("..."); 
           })
        }
    });
});