Is there a way in Vanilla JS to get each line of a text element when the page loads or when the window is resized?
Lets say for the element <h2>This is a beautiful example text</h2>
.
On mobile (with less space it breaks into several lines) would be displayed as:
This is a
beautiful
example text
and i would like to get an array like:
["This is a", "beautiful", "example text"]
if we resize the window, maybe on desktop, than the text would have a little bit more space so it needs to break in to less lines, maybe:
This is a beautiful
example text
and then i would like to get:
["This is a beautiful", "example text"]
i have tried something like:
let text = document.querySelector('.text').textContent;
let lines = text.split(/\r|\r\n|\n/);
but i always end up getting the whole string together like ["This is a beautiful text"]
.
I am trying to do this, because i need to style each line independently (yeap, crazy client wishes!), i cannot change the html and it needs to work when i resize the window. So i think i need to do it with JS, and somehow see how CSS is affecting the text and breaking it into several lines...
so, to clarify, what i am trying to get with JS with the text of each line, when the text breaks because of the container getting smaller. So the Element and the text are the same, but due to less space it breaks into different amount of lines.
Any ideas?
** === UPDATE === **
I can get the number of lines using .getClientRects()
. But what i am trying to do is get the text of each of the lines of the element