JavaScript – Visible Text of a DIV

Okay, I didn’t see the addendum to the question. Although I had previously said it wasn’t possible to do this using JavaScript and a font that isn’t fixed-width… it actually is possible!

You can wrap each individual character in a <span>, and find the first <span> that is outside the bounds of the parent. Something like:

function countVisibleCharacters(element) {
    var text = element.firstChild.nodeValue;
    var r = 0;

    element.removeChild(element.firstChild);

    for(var i = 0; i < text.length; i++) {
        var newNode = document.createElement('span');
        newNode.appendChild(document.createTextNode(text.charAt(i)));
        element.appendChild(newNode);

        if(newNode.offsetLeft < element.offsetWidth) {
            r++;
        }
    }

    return r;
}

Here’s a demo.

Leave a Comment

tech