Created
September 7, 2017 10:20
-
-
Save DimitryDushkin/525dca0408526a6ca1a48d7f1a1925ad to your computer and use it in GitHub Desktop.
Get lines from dom element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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