Is there an equivalent to getBoundingClientRect() for text nodes?
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();
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.)