Jefferdai
Jefferdai

Reputation: 3

How to get the rectangle of the text in an element of the web page (not the rectangle of the element itself)?

Sometimes the rectangle of the text in an element is different from the rectangle of the element itself. I want to get the rectangle of the text, not the one of element.

I tried two MDN functions: Element.getClientRects() and Element.getBoundingClientRect(), but they don't find the rectangle of the text.

For example, there is following button:

<button style="position:absolute; left:58px; top:224px; width:100px; height:40px;">

  Both the span and the paragraph have a border set.

</button><br/>

Both getClientRects and getBoundingClientRect only find the rectangle of button itself.

How can I find the rectangle of the text "Both the span and the paragraph have a border set."?

Upvotes: 0

Views: 450

Answers (1)

Kaiido
Kaiido

Reputation: 136638

Range API can give it to you, thanks to its getBoundingClientRect method:

const range = document.createRange();
const button = document.querySelector('button');
const textNode = button.firstChild;
range.selectNode( textNode );
// get the bounding box of the TextNode
const rect = range.getBoundingClientRect();

const border = document.getElementById('border');
border.style.top = rect.top + 'px';
border.style.left = rect.left + 'px';
border.style.width = rect.width + 'px';
border.style.height = rect.height + 'px';
#border {
  display: block;
  border: 1px solid;
  position: absolute;
}
<button style="position:absolute; left:58px; top:24px; width:100px; height:40px;">

  Both the span and the paragraph have a border set.

</button><br/>

<div id="border"></div>

Upvotes: 2

Related Questions