JavaScript Ranging Gone Wrong
Solution 1:
You need to expand function xxx to support IE, which it currently doesn't. The document.createRange
and window.getSelection
functions do not appear to work within this environment.
How about:
function xxx()
{
var myList = document.getElementsByTagName("div");
if(window.getSelection)
{
var range = document.createRange();
var start = myList[0];
var end = myList[0];
range.setStart(start, 0);
range.setEnd(end, 1);
window.getSelection().addRange(range);
}
else
if(document.selection)
{
document.selection.empty();
var txt = document.body.createTextRange();
txt.moveToElementText(myList[0]);
txt.setEndPoint("EndToEnd", txt);
var start;
txt.moveStart('character', start);
if (length + start > myList[0].innerHTML.length)
{
length = myList[0].innerHTML.length - start;
}
txt.moveEnd('character', -(myList[0].innerHTML.length - start - length));
txt.select();
}
}
The code will select the entire DIV element's text. You'll need to fiddle with the endpoints to get this to select only a portion of this range.
Solution 2:
First, I highly recommend Firebug for debugging Javascript on FireFox. It pointed me to the setEnd line immediately.
Now to the getting you to the answer. The second parameter of setStart and setEnd is the node depth to select into. Since you only have two div tags without any child nodes you only have depths 0 and 1. For myList[0] your depth 0 is the div tag itself and depth 1 is the text node within the div.
Since I'm not sure what you attempting to select here would be the corrected code for selecting all text within both div tags.
var end = myList[1];
range.setStart(start, 0);
range.setEnd(end, 1);
Post a Comment for "JavaScript Ranging Gone Wrong"