View Full Version : document.body.createTextRange(), selecting...

02-20-2003, 11:25 PM

A colleague and I are trying to find a way to automatically select ONLY a specific range of text within a page, using


and somehow referencing the id of a span... however NOTHING we have tried works. We got it to select the first thing sometimes (they may often contain the same text), and at other times it would select all spans with identical text - but we're finding it impossible to isolate the span by id and select the text just by clicking on the span. It's pretty perplexing, and this is not the type of javascript we usually mess around with... any help?

The below obviously doesn't work, just a general example of what we're trying to do... :mad:

<script type="text/javascript">
function textSelect(lblnumber)
var range = document.???.innerText;
// -->
<form id="form1" action="" method="post">
<span id="lblFasdffname" onclick="textSelect(this.id)"><*fname*></span>
<span id="lblFasd234name" onclick="textSelect(this.id)"><*fname*></span>
<span id="lblFasdasd3name" onclick="textSelect(this.id)"><*fname*></span>

02-21-2003, 12:37 AM

var range = document.body.createTextRange();

ugghhhh, look what you made me do. icky! :(

02-21-2003, 12:59 AM
Hey, I try to avoid this kind of icky stuff, myself, and the "Bible" didn't help much when you're trying to figure it out quick...

But that might help someone I'm working with, so thanks! :)

I'll let you know how it goes in the morning... but I suggested we post in this forum for obvious reasons. :)

02-21-2003, 04:25 AM
how is that icky??
whats wrong with doing it that way?

02-21-2003, 04:43 AM
Because IE-only stuff is generally icky. Especially TextRanges. There is a wonderful thing called DOM2 Range, and IE has do to their own thing with TextRange. Brings a bad taste to my mouth.

The DOM2 Range way of creating a range around some text using the same information:

var range = document.createRange();

Then you could surroundContents() with a styled span or something to indicate selection. (Selection is part of the browser, and not the webpage, therefore DOM doesn't deal with actual selections).

The Gecko way of selecting text:

var selection = window.getSelection();

Is only a little less icky because it provides an intelligent interface to user-selections, and uses DOM2 Range instances to describe them.

02-21-2003, 03:08 PM
Thanks, it works. We're also going to try to do some browser-checking so we can use the gecko method as well... :)

02-21-2003, 10:31 PM
That works just great too. :)