JSFiddle - React, Tailwind, and code Playground

by Turi S

HTML

<p id="targetElement">There is a long sentence here.
The sentence is so long that it overflows from the element.</p>

CSS

#targetElement{
   width:100px;
   height:50px;
   overflow-y:auto;
   position: relative;
}

JavaScript

var $elem = $('#targetElement');

alert(nthCharOffset($elem, 21));

function nthCharOffset($elem, charIndex) {
	var text = $elem.html();
  var pattern = new RegExp("^(.{"+charIndex+"})(.)");
  var newText = text.replace(pattern, '$1<span class="get-position-of-it">$2</span>');
  $elem.html(newText); //Set wrapper
  var offset = $(".get-position-of-it").position();
  $elem.html(text); //Place back
  return offset.top;
}