Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position and size of a HTML text node using javascript?

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?

like image 931
benjaminchanming Avatar asked Apr 25 '13 07:04

benjaminchanming


People also ask

How do I get the position of text in HTML?

“how to position text in html” Code Answer's 1)static: this is the default value. 2)sticky: the element is positioned based on the user's scroll position. 3)fixed: the element is positioned related to the browser window. 4)relative: the element is positioned relative to its normal position.

How do you retrieve a position of desired words from a string in CSS?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found.

How do you find XY coordinates of a div?

If the element is in the main document you can get the DIV's coordinates with... var X=window. getComputedStyle(abc,null). getPropertyValue('left'); var Y=window.


1 Answers

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>
like image 157
Tim Down Avatar answered Oct 11 '22 10:10

Tim Down