Reputation: 5179
I'm currently trying to limit the length of some dynamic titles on a project by using the following Jquery..
EDIT improvement via @Utkanos
$(document).ready(function() {
$(function(){
$(".newsTitle").each(function(i){
var len=$(this).text().length;
if(len>40) // If more than 35 characters then..
{
$(this).text($(this).text().substr(0,40)+'...'); // then add ...
}
});
});
});
I need to be able to limit the title length however not damage the link tags wrapped around the title. Is this possible? This is the HTML I am having to work with.
<h2 class="newsTitle">
<a href="/blog/new-story">Lorem Ipsum ameh dolor sit loremip ipsum</a>
</h2>
Upvotes: 0
Views: 100
Reputation: 108520
Change:
$(".newsTitle")
to:
$(".newsTitle a")
That way you are correctly manipulating the node that contains the text, not it’s parent that also contains the anchor element.
Upvotes: 2