22

Is there a way to get the bounding rect of a text node?

The getBoundingClientRect() method is defined on elements only, and the parent element is bigger then the actual text node.

GargantuChet
  • 5,691
  • 1
  • 30
  • 41
user163369
  • 265
  • 1
  • 2
  • 6

2 Answers2

36

If you don't need to support IE8 or older, you can use a Range to select the text node, and then get the bounding rect directly from the Range.

Example (should work in this page):

var text = document.querySelector('#question-header .question-hyperlink').childNodes[0];
var range = document.createRange();
range.selectNode(text);
var rect = range.getBoundingClientRect();
range.detach(); // frees up memory in older browsers

You can also reuse the Range object if you're doing this for multiple text nodes; just make sure not to call range.detach() until you're done. (Note: Range.detach() is now a no-op in the DOM standard, though some older browsers will still disable use of the range after its invocation.)

Noyo
  • 4,874
  • 4
  • 39
  • 41
11

Wrap the text node in a <span>, get the boundingRect of that span.

var span = document.createElement('span');
textNode.parentNode.insertBefore(span, textNode);
span.appendChild(textNode);
var rect = span.getBoundingClientRect();
eyelidlessness
  • 62,413
  • 11
  • 90
  • 94