user2774042 user2774042 - 3 months ago 9
HTML Question

using javascript to truncate a paragraph in div to 100 characters

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?

The script is below:

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


Solved:
Based on answers from @Lalinda Sampath and @Pavlo

<script>
function ellipsify (str) {
if (str.length > 10) {
return (str.substring(0, 10) + "...");
}
else {
return str;
}
}
var div = document.getElementById('target');
var div1 = document.getElementById('target1');
var div2 = document.getElementById('target2');
div.textContent = ellipsify(div.textContent);
div1.textContent = ellipsify(div1.textContent);
div2.textContent = ellipsify(div2.textContent);
</script>


and the usage of the following in html:

<div id="target">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
<div id="target1">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
<div id="target2">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

Answer

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 commodo 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:

Comments