Tom
Tom

Reputation: 8127

Get offset of node in whole html document in Javascript?

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.

Upvotes: 3

Views: 1321

Answers (1)

casablanca
casablanca

Reputation: 70701

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.

Upvotes: 7

Related Questions