1

When using the Selection Api, pseudo elements are sometimes not included in resulted getClientRects. As, @Kaiido has mentioned, Range#getClientRects() can sometimes only include selectable text.

This results in only selectable text being included.

var range = document.createRange();
range.selectNodeContents(e.target);
bounds = range.getBoundingClientRect();

Calling e.target.getBoundingClientRect() will included the entire elements box.

How can I retrieve a "selectable text" bbox similar to the Selection Api.

range.selectNodeContents(e.target);
bounds = range.getBoundingClientRect();

I'd like to avoid var styles = window.getComputedStyle(element,':after') if possible.

I also tried offsetWidth ect... but this also includes the pseudo element.

  • I don't think there is an easy way. Either the pseudo elements contribute to the element's box, and they're included in the `Element#getBoundingClientRect()` (and `getClientRects()`) results, either they're not in either (e.g because they have `position: absolute`). `Range#getClientRects()` will only give you the bbox of selectable texts, so it will indeed not correspond to the element's box. What were you trying to do with this info? Maybe there is a way around if we step back a little. – Kaiido Dec 04 '22 at 04:01
  • @Kaiido Thank you for your thoughts. This led me to https://stackoverflow.com/questions/6961022/measure-bounding-box-of-text-node-in-javascript, which I think might work for me over the messiness of window.getComputedStyle. The rects are being used to render a custom selection range using canvas for a hex/memory viewer, where the data shown is formatted into groups/columns via :nth-child and item:after. So getting only the "selectable texts" is really what I'm looking for. Thanks again for your time. Will update shortly. – undercover grill Dec 04 '22 at 05:59

0 Answers0