Search code examples
javascripthtmlcssellipsis

Get clamped (with ellipsis) textContent from textNode


How can I get the clamped text from a node in javascript? See below code:

console.log(document.getElementById("text1").textContent);
// prints "This is a long text"


console.log(document.getElementById("text2").textContent);
// prints "This is a long text as well"
// expected "This is a long text a..."
.longtext {
    width: 140px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
<div id="text1">This is a long text</div>
<div class="longtext" id="text2">This is a long text as well</div>

I want to get the expected "This is a long text a..." from the element with id text2.


Solution

  • I found similar question: How can I access the actual text that is displayed in a DIV when using CSS style overflow: hidden?

    In short:

    There's no easy way to do it. You have to calculate how much text can be visible in the DIV based on div size, font size, font type and text offset inside div

    How to do ellipsis by js http://www.ruzee.com/blog/2007/08/ellipsis-or-truncate-with-dots-via-javascript