title: How to count chars in a CSS limited div with JS
body: <p>I have the following CSS:</p>
  <pre class="lang-css prettyprint-override"><code>html {
    --lh: 18px;
  }
  
  .line-10 {
    --max-lines: 10;
  
    max-width: 100%;
    max-height: calc(var(--lh) * var(--max-lines));
    overflow: hidden;
  }
  
  </code></pre>
  <p>and want to count chars in a div:</p>
  <pre class="lang-js prettyprint-override"><code>const div = document.createElement('div')
  div.classList.add('line-10')
  div.innerHTML = longHtml
  const _createdHTML = div.innerHTML
  const _createdTxt = _createdHTML.replace(/&lt;[^&gt;]*&gt;/g, '')
  console.log('_createdTxt', _createdTxt.length)
  </code></pre>
  <p>but I am getting the entire <code>longHtml</code> instead of limited by CSS. Any way to solve that?</p>
  <p>Current solution for case A (1 big paragraph of text per div):</p>
  <pre><code>const maxLines = 10
  const fullTxtLen = html.replace(/&lt;[^&gt;]*&gt;/g, '').length
  const fullLineLen = 150 // or whatever fits into initial div
  
  if (fullTxtLen / fullLineLen &gt; maxLines) {
    const totalLines = fullTxtLen / fullLineLen
    const reduceIn = totalLines / maxLines
    const final = fixHtml(html.substring(0, parseInt(html.length / reduceIn)))
  
    return {
      html: final,
      len: final.replace(/&lt;[^&gt;]*&gt;/g, '').length // i.e. this is the answer on visible char count
    }
  }
  
  function fixHtml (html) {
    const div = document.createElement('div')
    div.innerHTML = html
    return (div.innerHTML)
  }
  </code></pre>
  <p>Problems with this solution:</p>
  <ol>
  <li>than introducing more <code>&lt;p&gt;</code> and/ or <code>&lt;br /&gt;</code>, it will make it pretty unreliable due to different <code>fullLineLen</code> for each line that does not end that the div right border.</li>
  <li>reduced char length is in text characters, not html characters</li>
  </ol>
  <h2>FAQ</h2>
  <h3>how many characters you need to keep, input examples and expected outputs</h3>
  <p>It depends on the size of the div. Input examples: 1) lorem ipsum in one paragraph, 2) lorem ipsum broken into different paragraphs. Expected output - visible char count.</p>