Question

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.

Was it helpful?

Solution

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();

OTHER TIPS

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top