views:

573

answers:

5

Hi,

Is it possible to retrieve the geometric position (i.e. top/left offsets from either the parent element, the page, etc) of a text node?

A: 

Have a look at this article - it uses the offsetParent property to recursively figure out the offset.

I would always recommend jquery over rolling your own methods for browser-varying stuff like this. The jquery CSS functions seem to have the methods you need!

Jennifer
Unfortunately, DOM text nodes do not seem to have offsetLeft/offsetTop properties. And jQuery doesn't handle text nodes nicely, too: I couldn't find out how to write a selector expression for them (nevermind that children() doesn't return text nodes).
David Parunakian
A: 

Also take a look at this article on MSDN as it considers padding and margins also

Scott Evernden
A: 

There isn't any built-in, cross-browser way to do this. I would use jQuery with the Dimensions plugin: http://brandonaaron.net/docs/dimensions/

It is cross-browser and will give you height, width and x & y offsets, among others.

nicholaides
+3  A: 

Not directly. TextNode does not have the originally-IE offset* (and similar) extensions for measuring on-viewport positioning.

On IE only, you could create a TextRange object, laboriously attempt to align it with the bounds of the TextNode, then measure the boundingLeft/boundingTop of the TextRange, and add it to the position of the parent element (obtained by the usual means). However this is a bunch of work for a potentially-wobbly single-browser solution.

Another approach you might be able to get away with would be wrapping the text in a span element (either in the document, or dynamically and/or temporarily by script), and using the span to measure positioning, assuming it's not picking up any additional styles that may affect the position. Note however that a wrapped span may not give the expected right/bottom values; depending on what you want to do with it, you might end up wrapping the first and last character or some other arrangement.

In summary: urgh, nothing good.

bobince
A: 

Just to close this: for now, I haven't found a way to do so, except wrapping every text node in its own span or another dimensional element. However, the task I had at the time of asking the question can be solved with other means.

David Parunakian