1

How can I get functionality equivalent to that of range.startOffset in Internet Explorer 8 and below?

I.e., I'd like a function I can call on a range that will tell me how many characters into its container the range starts.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
Tom Lehman
  • 85,973
  • 71
  • 200
  • 272
  • `range.startOffset` is an offset relative only to its immediate container, and is a character offset only if the container is a text node. Is that what you want? – Tim Down Jan 27 '11 at 00:18
  • @Tim: you're right; this isn't what I want. I created a new question: http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container – Tom Lehman Jan 27 '11 at 00:36

2 Answers2

5

If you want a DOM Range implementation in IE, you could use my Rangy library: http://code.google.com/p/rangy/.

var range = rangy.getSelection().getRangeAt(0);
alert(range.startOffset);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

Here an example-code, see the comments inside:

<html>
<head>
<title>Test</title>
<script type="text/javascript">
<!--
function fx()
{  
    //create a range of selection
  var rng = document.selection.createRange();
    //if nothing is selected return null
  if(rng.text=='')return null;
    //create a second range of selection
  var rng2 = document.selection.createRange();
    //let the 2nd range  encompass the whole element
  rng2.moveToElementText(rng.parentElement())
    //move the end-point of the 2nd range to the start-point of the 1st range
  rng2.setEndPoint('EndToStart', rng);
    //return the length of the text in the 2nd range
  return(rng2.text.length);
}
//-->
</script>
</head>
<body>
<input type="button" onclick="alert(fx())" value="select some text below and then click me">
<p>1234<b style="color:red">5678</i>90</p>
</body>
</html>
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • That's not exactly equivalent to a Range's `startOffset`, which is relative only to its immediate container node. However, it may well be what the OP wants, which is harder to achieve in other browsers. – Tim Down Jan 27 '11 at 00:15
  • So is this an IE-specific answer to this question: http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container? – Tom Lehman Jan 27 '11 at 00:37
  • This is an IE-specific answer to your IE-specific question here. – Dr.Molle Jan 27 '11 at 02:26