5

Consider a simple html element as

<div id="test">
a long text without line break
</div>

The browser will create lines based on the glyph and font sizes. After text arrangement by the browser (e.g. depending on the window width), how to get the lines of the text by JavaScript?

For example:

  1. How to get the total number of lines
  2. How to get the first line as appeared in the current window?
  3. How to get the nth line?
Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23
Googlebot
  • 15,159
  • 44
  • 133
  • 229

3 Answers3

4

No, there is no API that gives you access to the rendered text after layout has occurred. The only way to approximate this is pretty hacky, i.e. add words into a container one at a time and see when it changes height. See this related question:

detecting line-breaks with jQuery?

Yeah, who'd have thought it, even jQuery doesn't do this! ;-)

Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232
2

2 easy solutions and a extremely hard one.

1 Formatting the text.

Inside a pre & textContent

html

<pre>hello
hello1
hello2</pre>

js

document.getElementsByTagName('pre')[0].textContent.split('\n')

http://jsfiddle.net/gq9t3/1/


2 Adding br's

Inside a div with br & textContent

html

<div>hello<br>hello1<br>hello2<br>pizza</div>

js

document.getElementsByTagName('div')[0].innerHTML.split('<br>')

http://jsfiddle.net/gq9t3/4/


To much trouble

css

div{width:100px;line-height:20px;}

html

<div>hello dfgfhdhdgh fgdh fdghf gfdh fdgh hello1gfhd gh gh dfghd dfgh dhgf gf g dgh hello2</div>

js

document.getElementsByTagName('div')[0].offsetHeight/20

easy way to find the number of lines but you need to calculate the text width to find the corresponding line content.

http://jsfiddle.net/gq9t3/3/

cocco
  • 16,442
  • 7
  • 62
  • 77
  • I want to get how the browser has arranged the lines, now breaking the lines myself. – Googlebot Jan 06 '14 at 14:48
  • yeah i understand.but there is to much work behind that.I talked about that in 2-3 answers. http://stackoverflow.com/a/20691677/2450730 http://stackoverflow.com/a/20792951/2450730 ... it's almost impossible what you wanna do. those answers talk more about text formatting. but the point is you have no control over the browsers formatting. each browser is different. the only way is to calculate everything. – cocco Jan 06 '14 at 14:53
  • the 3th solution is the base answer of your question.1.get the line height,2.for each word calculate the width and add that to a new element,3.if the width is bigger than the max width create a new element(line)... and so on. – cocco Jan 06 '14 at 14:58
-1

I was attempting to style the first line of text, but text-transform:uppercase messed it up. http://zencode.in/lining.js/ helped with addressing the first line (responsively!), so perhaps this library will assist with your issue too.

Mark Hewitt
  • 187
  • 1
  • 4