jquery - Shrink a text if more than 10 characters length -
hi have following <h2>
"example example example example". want detect lenght of <h2>
, if it's more 10 characters, shrink "example ex...". it? shrink 10 characters long , add "..." end.
here's code:
html
<h2>example example example example example</h2> <h2>example</h2>
jquery
$(document).ready(function(){ var dtl = $('.h2').text().length; if(dtl>10){ $('.h2').text().length = 10; $('.h2').text($('.h2').text()+"..."); } });
but that's not working...
you need use substr in case:
and have h2
tag elements , not .h2
classname.
$(document).ready(function(){ var dtl = $("h2").text().length; if(dtl>10){ $('h2').text($('h2').text().substr(0,10)+"..."); } });
am doing 1 element, may need use $("h2").each()
target elements.
more complete code:
$(document).ready(function(){ $("h2").each(function() { if($(this).text().length > 10) { $(this).text($(this).text().substr(0,10)+"..."); } }); });
demo
$(document).ready(function(){ $("h2").each(function() { if($(this).text().length > 10) { $(this).text($(this).text().substr(0,10)+"..."); } }); });
<!doctype html> <html> <head> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <meta charset="utf-8"> <title>js bin</title> </head> <body> <h2>example example example example example</h2> <h2>example</h2> </body> </html>
Comments
Post a Comment