最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - using javascript to truncate a paragraph in div to 100 characters - Stack Overflow

programmeradmin1浏览0评论

I have found the following script to limit / truncate my paragraphs of more than 400 chracters located in a <div> to 200 character. But i can't figure out how to incorporate it in html!

How is this done?

Following is the script:

<script>
function ellipsify (str) {
    if (str.length > 10) {
        return (str.substring(0, 10) + "...");
    }
    else {
    return str;
}
}
</script>

I have found the following script to limit / truncate my paragraphs of more than 400 chracters located in a <div> to 200 character. But i can't figure out how to incorporate it in html!

How is this done?

Following is the script:

<script>
function ellipsify (str) {
    if (str.length > 10) {
        return (str.substring(0, 10) + "...");
    }
    else {
    return str;
}
}
</script>
Share Improve this question edited Aug 4, 2016 at 16:23 Pavlo 45k14 gold badges83 silver badges114 bronze badges asked Aug 4, 2016 at 14:49 user2774042user2774042 1351 silver badge7 bronze badges 5
  • 1 if you dont care about the 100 chars but care about the space left in the element you can use css: text-overflow: ellipsis; – Roland Starke Commented Aug 4, 2016 at 14:55
  • 1 First you need to assign the text in div to a variable in JavaScript and pass that variable to the above function. – ONE_FE Commented Aug 4, 2016 at 15:04
  • Pavlo showed in the answer for the usage of id. But @Lalinda Sampath it only truncates the first div! How can the script be changed to change all divs? – user2774042 Commented Aug 4, 2016 at 15:12
  • 1 make your second div's id as 'target2'. Then, var div2 = document.getElementById('target2'); – ONE_FE Commented Aug 4, 2016 at 15:24
  • That did it. Thank you @Lalinda Sampath – user2774042 Commented Aug 4, 2016 at 15:37
Add a ment  | 

1 Answer 1

Reset to default 4

Assuming that the div has id of "target":

function ellipsify (str) {
    if (str.length > 10) {
        return (str.substring(0, 10) + "...");
    }
    else {
    return str;
}
}

var div = document.getElementById('target');
div.textContent = ellipsify(div.textContent);
<div id="target">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea modo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

More information about API's used:

  • document.getElementById
  • Node.textContent
发布评论

评论列表(0)

  1. 暂无评论