'How to get the width of a line of multi-line text use Javascript

Line f.e.:

    <p style="width: 300px;">asdasd sa das d asd a sd as das dasdasdasdasd saddasdasdasdasd asdasdsd</p>

The width of P is 300px but each of the lines is smaller. I need to calculate it for each line. Screen: multiline block



Solution 1:[1]

I do not know js way but you can use jquery for that:

   <p id="demo" style="white-space:pre">
    Line 1

    Line 2

    Line 3

    Line 4 Blah

    Line 5
    </p>

JQUERY:

  $(function(){
var text =  $.trim($('#demo').text());
// this may vary browser to browser...
var text_w_no_empty_lines = text.replace(/[\r\n]+/g, '\n');
var lines = text_w_no_empty_lines.split('\n');
// line number you want  total - 1
var line_5 = lines[4];
// .tick { white-space:nowrap;display:inline-block;display:none }
alert( $('<p class="tick">').html(line_5).appendTo('body').width() )
}
);

Solution 2:[2]

Maybe too late but, I had the same request, and I thought a solution. When you make a selection to a div, you can get the bounding rects, of every selection box, so, if you have multiple line you get the width and the position of every line.

window.getSelection().selectAllChildren(document.querySelector("p#element"));
var selection = window.getSelection();
var range = selection.getRangeAt(0); 
var rects = range.getClientRects();
console.log(rects);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T. Emre Yildirim
Solution 2