Search code examples
javascriptdombounding-boxtextnode

Is there an equivalent to getBoundingClientRect() for text nodes?


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.


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