Reputation: 374
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!
Upvotes: 6
Views: 1218
Reputation: 324567
You can't really do this in a sensible way. The fundamental problem is that there is no way in browsers to get back the original HTML sent by the server; innerHTML
is often different in some way because it is a representation of the browser's DOM parsed from the original HTML rather than a snippet of the original HTML.
It is possible to retrieve information about the user's selection in all major browsers but this information is expressed in terms of nodes in the browser's DOM rather than as offsets relative to a string containing the original HTML sent by the server.
All that being the case, your best option is retrieving the HTML source again via Ajax and doing complicated HTML parsing to match the browser DOM up with your HTML string, which is non-trivial. It could also be impossible if script running in your page has modified the DOM by the time you get the HTML source back. I would suggest trying to find another way to achieve what you want.
Upvotes: 1
Reputation: 516
<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>
Upvotes: 1
Reputation: 3955
this 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/
Upvotes: -1