Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 975
user163369 Avatar asked Sep 22 '09 16:09

user163369


People also ask

What is getBoundingClientRect () in Javascript?

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport. The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.

What is getBoundingClientRect relative to?

getBoundingClientRect() gives a result relative to the viewport's top-left corner ( 0,0 ), not relative to an element's parent, whereas el.

What is a text node?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.

Does getBoundingClientRect include padding?

Border, padding and margin are not included.


2 Answers

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

like image 143
Noyo Avatar answered Oct 21 '22 23:10

Noyo


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();
like image 21
eyelidlessness Avatar answered Oct 21 '22 22:10

eyelidlessness