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?

benjaminchanming
  • 538
  • 5
  • 17
  • You can get the div position and then you'll have to add any top and left padding and border. – Asken Apr 25 '13 at 07:52
  • @user125697: `text` is a node , not an element. It doesn't duplicate of that question. – benjaminchanming Apr 25 '13 at 07:59
  • [this](http://stackoverflow.com/questions/7913631/jquery-get-position-of-character-in-a-div) may help you – anpsmn Apr 25 '13 at 08:02
  • @Asken: How to get the padding and border information? I cannot find its padding and border value using the inspector of Chrome. – benjaminchanming Apr 25 '13 at 08: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. – Tim Down Apr 26 '13 at 11:55

1 Answers1

36

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>
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Is this code work with old browser. if not, what solution for old browser. – Domezchoc Nov 26 '14 at 05:21
  • 1
    @Domezchoc: Which old browsers? There is a solution using [`TextRange`](http://msdn.microsoft.com/en-us/library/ie/ms535872%28v=vs.85%29.aspx) 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. – Tim Down Nov 26 '14 at 09:16
  • i mean IE, i got it. first i need to find TextRange and then getClientRects. thank – Domezchoc Nov 27 '14 at 06:12
  • 1
    @user984003: The snippet seems to work OK on Safari in iOS 11. – Tim Down Oct 31 '17 at 11:08