Skip to content

Instantly share code, notes, and snippets.

@DimitryDushkin
Created September 7, 2017 10:20
Show Gist options
  • Save DimitryDushkin/525dca0408526a6ca1a48d7f1a1925ad to your computer and use it in GitHub Desktop.
Save DimitryDushkin/525dca0408526a6ca1a48d7f1a1925ad to your computer and use it in GitHub Desktop.
Get lines from dom element
function getTextLinesFromElement(target) {
const originalHtml = target.innerHTML;
const lines = [];
let currentLine = [];
let prevWordTop;
target.innerHTML = target.textContent.split(' ').map(w => `<span>${w}</span>`).join(' ');
Array.from(target.querySelectorAll('span')).forEach((span, i , spans) => {
const text = span.textContent;
if (text === '') {
return;
}
const top = span.offsetTop;
if (typeof prevWordTop === 'undefined') {
prevWordTop = top;
}
if (prevWordTop !== top) {
lines.push(currentLine.join(' '));
currentLine = [];
prevWordTop = top;
}
currentLine.push(text);
});
lines.push(currentLine.join(' '));
target.innerHTML = originalHtml;
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment