JSFiddle - React, Tailwind, and code Playground
HTML
<p id="sampleParagraph">Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects.Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects.Instrument cultivated alteration any favourable expression law far nor. Both new like tore but year. An from mean on with when sing pain. Oh to as principles devonshire companions unsatiable an delightful. The ourselves suffering the sincerity. Inhabit her manners adapted age certain. Debating offended at branched striking be subjects.</p>
JavaScript
function getLine(paragraphId, lineNum) {
lineNum--;
var elem = document.getElementById(paragraphId);
var spanChildren = elem.getElementsByTagName("span");
var paragraphText = elem.innerHTML.replace(/(\r\n|\n|\r)/gm, "");
var newParagraphText = "";
var words = [];
if (spanChildren.length === 0) {
words = paragraphText.split(" ");
for (var i = 0; max = words.length, i < max; i++)
newParagraphText += '<span>' + words[i] + "</span> ";
elem.innerHTML = newParagraphText;
}else{
for(var i=0; max = spanChildren.length, i<max; i++){
words[words.length] = spanChildren[i].innerHTML;
}
}
var lineCounter = 0;
var previousY = spanChildren[0].offsetTop;
var returnText = "";
var startReturning = false;
for (var i = 0; max = words.length, i < max; i++) {
if (spanChildren[i].offsetTop != previousY) lineCounter++;
if (lineCounter === lineNum) startReturning = true;
if (lineCounter !== lineNum && startReturning) return returnText.substring(0, returnText.length - 1);
if (startReturning) {
returnText += words[i] + " ";
if (i + 1 === words.length) return returnText.substring(0, returnText.length - 1);
}
previousY = spanChildren[i].offsetTop;
}
}
alert(getLine("sampleParagraph", 5));
alert(getLine("sampleParagraph", 4));