You're almost there! Your condition is not checking against the length of the text in the div. You are checking the .length
of the jQuery object, which would be equal to 1
(number of elements found by the selector). You need to check against the length of the actual text inside the div
. Get rid of the if
outside and move the length-check inside the function that you pass into .text()
:
$(".trim").text(function(index, text) {
var newText = text;
if(text.length > 40) {
newText = text.substr(0, 40) + "...";
}
return newText;
});