views:

61

answers:

1

I'm looking for a way to get the offset relative to the whole document for a given node with Javascript. Eg.:

<html><head></head><body><div id="mainContent"><h1 id="myTitle">Title</h1><p>First paragraph</p><p>Second <b>paragraph</b></p></div></body></html>

Then (using JQuery):

$("#myTitle").getDocumentOffset()

should return 47 because the h1 with id myTitle starts at offset 47 in characters relative to the whole document.

Any idea how to accomplish this?

Thanks in advance.

+5  A: 

This question doesn't make sense because extra whitespace is ignored in HTML documents and hence the same page could be represented in several ways. For example, this:

<html>
  <body></body>
</html>

is equivalent to this:

<html><body></body></html>

Further, once the browser has parsed your code, there is no way to retrieve the original HTML markup (with the same whitespace) that was present in the source file. This means the "offset" you're looking for isn't uniquely defined.

casablanca
Is it never possible to get the unparsed HTML? If so, would it be possible to get the offset of a trimmed body? (only counting from the body, no whitespace except spaces) - Update: when I log $('html').html(), whitespace does seem to be reserved. Eg. when I add 5 tabs it shows these 5 tabs. It also shows Javascript, etc.
Tom
Or better: $(document).children().html()
Tom
@Tom: There is no guarantee that it will work. For example, Firefox seems to retain formatting, while both IE and Chrome strip spaces according to their liking. And getting the offset from a "trimmed body" is not easy: you essentially have to write your own DOM parser.
casablanca
@Tom: @casablanca is correct. Also, the offset you want doesn't seem useful to me. Considering the document as a string of HTML is rarely as reliable or useful as considering it as a tree of nodes.
Tim Down
@ Tim Down, this is related to my previous question. The reason I need it in a string is because I have to use this information in a different program on my server, which does not have a DOM parser.
Tom
@Tom: The problem is that you can't reliably get the exact HTML that was sent to the browser in JavaScript, as @casablanca points out.
Tim Down