JSFiddle - React, Tailwind, and code Playground
HTML
<div>
depending on whether the element gets word wrapped (which depends on its width and the value of various css properties such as white-space, word-break, overflow-wrap, etc).
Is there a way to determine how has the browser rendered the text in such an element with respect to word wrapping? i.e., I am looking for javascript code that would return something like ["foo", "bar"] (in the case wrapping did occur).
It seems that getClientRects returns separate boxes for each line (it appears to be working for inline elements only). But I am looking something that also gives information about the text.
</div>
CSS
div {
white-space: pre-wrap;
}
JavaScript
function showLines(e) {
const el = e.target,
node = el.firstChild,
range = document.createRange(),
len = e.target.textContent.length,
texts = [];
let hTracker, y, oldY;
range.selectNodeContents(el);
range.collapse();
hTracker = range.cloneRange();
hTracker.setEnd(node, 1);
oldY = hTracker.getBoundingClientRect().height;
for (let n = 0; n < len; n++) {
hTracker.setEnd(node, n);
range.setEnd(node, n);
y = hTracker.getBoundingClientRect().height;
if (y > oldY || n === len - 1) {
// Line changed, resume the previous range (not when at the end of the text)
range.setEnd(node, n - (n !== len - 1));
// Store the text of the line
texts.push(range.toString());
// Set the start of the range to the end of the previous line
range.setStart(node, n - 1);
oldY = y;
}
}
console.log(texts);
};
document.addEventListener('click', showLines);