JSFiddle - React, Tailwind, and code Playground
HTML
<div class="longText">Very long text here</div>
<div class="longText">Very long text here as well</div>
<div class="longText">And the text here is even longer</div>
JavaScript
function cutString(element){
var text = element.innerText; // We fetch innerText to omit any HTML from the length check
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
element.title = text; // we set the value of title to allow tooltip hovering of full text
element.innerText = strShort + "...";
}
}
var longTextElems = document.getElementsByClassName('longText'); // This will return a collection of HTML elements
console.log(longTextElems.length);
for(count = 0; count < longTextElems.length; count++) {
cutString(longTextElems.item(count));
}