0

I have dom element in html page with unknown structure, for example:

let element = document.getElementById('element');
<div id="element">
  <span>some word here</span>
</div>

Note that there can be any number of nesting divs.

I know two indexes start, end such that element.innerHtml.substring(start, end) is some word. I want to know bound rect of this word (that is left, top, width and height). I tried something like this:

let element = document.getElementById('element');

let start = 14;
let end = 18;

// prints `word`
console.log(element.innerHTML.substring(start, end));

let range = document.createRange();
range.setStart(element, start);
range.setEnd(element, end);
console.log(range.getBoundingClientRect());
<div id="element">
  <span>some word here</span>
</div>

But this doesn't work. How can I get bound rect without any recursion and without wrapping word in <span>?

diralik
  • 6,391
  • 3
  • 28
  • 52
  • Possible duplicate of [Get the position of text within an element](https://stackoverflow.com/questions/5143534/get-the-position-of-text-within-an-element) – ControlAltDel Sep 21 '17 at 19:15
  • @ControlAltDel That question is only about x and y coordinates...OP wants the entire `DOMRect` object for the substring. I dont think this is a duplicate. – Tejasvi Karne Sep 21 '17 at 19:19

0 Answers0