Getting selected offset of html element related to html source code using js

Is it possible to get the offset of the selected html element in the HTML source code?

eg:

<html> <body> <a href="http://google.com">google</a> </body> <html>

if the user selects google text, I would like to get 40, since this is the offset from the beginning of the source.

I tried with the Range object, but couldn't find anything useful with this.

Thank!

+5
source share
3 answers
<html>
<head>
<script>
function srcOffset(ele)
{
   alert(document.getElementsByTagName('html')[0].innerHTML.indexOf(ele.id) + ele.id.length + 2);
   return false;
}
</script>
</head>
<body>
<a href="http://www.google.com/" onclick="return srcOffset(this)" id="myLink">Google</a>
</body>
</html>
+1
source

. , HTML-, ; innerHTML , DOM , HTML, HTML.

, DOM , , HTML, .

, , - HTML Ajax HTML, DOM HTML, . , script, , DOM HTML. , .

+1

this is how you get the offset using jQuery

$(document).ready(function() {
  $("a").click(function() {
   var offset = $(this).offset();
   alert(offset.left);
      alert(offset.top);
});

});​

<html> <body> 
    <a href="http://google.com" class="first">google</a> 
    <a href="http://abc.com" class="second">abc</a> 
    <a href="http://xyz.com" class="third">xyz</a> 
</body> <html>​

a.first { position:absolute;
    left:20px; top:35px; }
a.second{ position:absolute;
          left:100px; top:35px; }
a.third{ position:absolute;
          left:220px; top:35px; }

Demo of this example: http://jsfiddle.net/5YFxH/

-1
source

All Articles