0

Let's say I have the div element, inside which there is some text. Is it possible to figure out the length of the text itself? Quite often the length of the div is a lot bigger than the length of the text inside? Here is the image of such div.

The pure javascript solution to that would be great!

ganqqwerty
  • 1,894
  • 2
  • 23
  • 36

2 Answers2

1

Welp, your div is a block element, so if you use Javascript to get the width, it will be of the entire div. I would recommend wrapping your inner text with <span> (inline elements) then look at the width of the span.

<div><span id="foo">Lorem ipsum</span></div>
<script>var width = document.getElementById('foo').offsetWidth;</script>

BTW, I just copied the code from How do I retrieve an HTML element's actual width and height?.

Community
  • 1
  • 1
Phil Tune
  • 3,154
  • 3
  • 24
  • 46
1

Try this to get the length of text inside div

<html> 
 <head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
 </script>
  <script>
    $(document).ready(function (){
      if ($('#test').text().length > 0) 
       alert($('#test').text().length);
    });
  </script> 
  </head> 
  <body> 

    <div id='test'>28</div>


  </body>
  </html>