In Firefox, you can use the Range object, as specified by W3C.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Range test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">→ Click here! ←</span>
<!-- Yes, I know, ‘Click here!’ is an evil message -->
<script>
var testCase = function () {
var userSelection;
if (window.getSelection) { // W3C default
userSelection = window.getSelection();
} // an extra branch would be necessary if you want to support IE
var textNode = document.getElementById('test').firstChild;
var theRange = document.createRange();
// select 10th–15th character (counting starts at 0)
theRange.setStart(textNode, 9);
theRange.setEnd(textNode, 14);
// set user selection
userSelection.addRange(theRange);
};
window.onload = function () {
var el = document.getElementById('trigger');
el.onclick = testCase;
};
</script>
</body>
</html>
Note that you have to get the TextNode
to set the selection, which is the firstChild
of the <p>
element. Also note that this example will not work in IE, you have to use some proprietary methods. A nice introduction is on QuirksMode.