JSFiddle - React, Tailwind, and code Playground
HTML
<div id="text">asdf</div>
<input id="input" value="asdf"></input>
<div id="results"></div>
JavaScript
function log(rect) {
$("#results").append("\r\n" + JSON.stringify(rect));
}
// Must use the text node, not the parent div. Works!
var r1 = document.createRange();
var textNode = $("#text")[0].childNodes[0];
r1.setStart(textNode, 0);
r1.setEnd(textNode, 2);
log(r1.getBoundingClientRect());
// No text node
var r2 = document.createRange();
var input = $("#input")[0];
r1.setStart(input, 0);
// r1.setEnd(input, 2); throws because there is no child at 2
// Gives a bounding rect of all 0s
input.setSelectionRange(0, 2);
var s = window.getSelection();
var r3 = s.getRangeAt(0);
log(r3.getBoundingClientRect());