21

For Example,

<div style="width:100px;text-align:center">text</div>

I want to get the position and size of the text text node , not its div wrapper. Is it possible?

5
  • You can get the div position and then you'll have to add any top and left padding and border. Commented Apr 25, 2013 at 7:52
  • @user125697: text is a node , not an element. It doesn't duplicate of that question. Commented Apr 25, 2013 at 7:59
  • this may help you Commented Apr 25, 2013 at 8:02
  • @Asken: How to get the padding and border information? I cannot find its padding and border value using the inspector of Chrome. Commented Apr 25, 2013 at 8:03
  • 1
    This is not a duplicate. Finding the position/dimensions of a text node is a different problem from doing the same with an element. Commented Apr 26, 2013 at 11:55

1 Answer 1

37

In modern browsers (recent-ish Mozilla, WebKit and Opera) you can use the getClientRects() method of a DOM range that encompasses the text node.

var textNode = document.getElementById("wombat").firstChild;
var range = document.createRange();
range.selectNodeContents(textNode);
var rects = range.getClientRects();
if (rects.length > 0) {
    console.log("Text node rect: ", rects[0]);
}
<div id="wombat">Wombat</div>

Sign up to request clarification or add additional context in comments.

4 Comments

Is this code work with old browser. if not, what solution for old browser.
@Domezchoc: Which old browsers? There is a solution using TextRange in IE which is easy so long as your text node is the only child of an element. Otherwise, it's still possible but more work to create the TextRange.
i mean IE, i got it. first i need to find TextRange and then getClientRects. thank
@user984003: The snippet seems to work OK on Safari in iOS 11.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.