JSFiddle - React, Tailwind, and code Playground

by Paulpro

HTML

<div id="thediv">This is my text inside a div and I want the overflow of the text to be cut</div>

CSS

div{
    width: 302px;
    height: 20px;
    overflow: hidden;
    white-space: nowrap;
}

JavaScript

function count_visible(el){
    var real_width = el.clientWidth;
    var text = el.childNodes[0].data;
    var min = 0;
    var max = text.length - 1;
    
    var tmp = document.createElement('div');
    var node = document.createTextNode();
    tmp.appendChild(node);
    document.body.appendChild(tmp);
    
    if(getComputedStyle)
        tmp.style.cssText = getComputedStyle(el, null).cssText;
    else if(el.currentStyle)
        tmp.style.cssText = el.currentStyle.cssText;
    
    tmp.style.overflow = 'visible';
    tmp.style.width = 'auto';
    
    var mid, width;
    for(;;){
        mid = (min + max)/2;
        node.data = text.substr(0, mid);
        console.log(max);
        width = tmp.clientWidth;
        if(width < real_width)
            min = mid + 1;
        else if (width > real_width)
            max = mid - 1;
        else
            return mid;
        console.log(max);
        break;   
    }
}

count_visible(document.getElementById('thediv'));