Mike S Mike S - 5 months ago 28
HTML Question

truncate paragraph in each div

I am new in html, and I want to set all character in every paragraph just 30 chars. My idea is truncate it, but I face a problem how to truncate all paragraph.

This my code

<div class="" id="my-gallery-container">
<div class="item h200" data-order="31">

<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">

<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>

<div class="item h200" data-order="30">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">

<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>


<div class="item h200" data-order="29">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">

<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>


<div class="item h200" data-order="28">
<div class="img-85">
<img src="images/Round David Michael Setyadarma.png">

<p class="parg">1 Qui habitat in protectione Altissimi, sub umbra Omnipotentis commorabitur. 2 Dicet Domino: “ Refugium meum
et fortitudo mea, Deus meus, sperabo in eum ”.
</P>
</div>
</div>


and this is my script under that code

<script type="text/javascript">

function truncateText(selector, maxLength)
{
var element = document.querySelector(selector),
truncated = element.innerText;

if (truncated.length > maxLength)
{
truncated = truncated.substr(0,maxLength) + '...';
}
return truncated;
};

document.querySelector('p').innerText = truncateText('p', 30);


</script>


but it works only the first paragraph
<p>
, how to truncate all
<p>
? anyone can help me?
Thank you

I hope I didn't repost

Answer

Is this what you're looking for?

function truncateText(selector, maxLength) {
    // Get all the paragraphs on page
    var paras = document.getElementsByTagName(selector);

    // Loop over paragraphs
    for (var i = 0; i < paras.length; i++) {
        // Get the text of each paragraph element
        var text = paras[i].innerText;

        // Use javascripts substring to trim it and 
        // set it back as the text of the paragraph element
        paras[i].innerText = text.substring(0,maxLength)
    }
}

// Input the p tag
truncateText('p', 30)

https://jsfiddle.net/t68gue8g/2/
If this is what you want, press the green tick.