Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the selected html element offset related to the html source code with js

Tags:

javascript

Can I get the offset of a selected html element in the html source code?

for example:

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

if the user would select the google text, I would want to get 40 as this is the offset from the start of the source.

I tried with Range object but couldn't find something helpful with this one.

Thanks!

like image 947
adi ohaion Avatar asked Nov 14 '22 09:11

adi ohaion


1 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>
like image 59
MarkFisher Avatar answered Nov 16 '22 02:11

MarkFisher