How to get the position of text within an element?

You can use ranges to find the position of elements. Quick jsfiddle here: https://jsfiddle.net/abrady0/ggr5mu7o/

var range = document.createRange();
range.setStart(parentElt, start);
range.setEnd(parentElt, end);
// These rects contain the client coordinates in top, left
var rects = range.getClientRects();

Edit: modified to print out the coordinates of the matched rect

Leave a Comment