In this chapter we’ll cover selection in the document, as well as selection in form fields, such as <input>.
JavaScript can access an existing selection, select/deselect DOM nodes as a whole or partially, remove the selected content from the document, wrap it into a tag, and so on.
You can find some recipes for common tasks at the end of the chapter, in “Summary” section. Maybe that covers your current needs, but you’ll get much more if you read the whole text.
The underlying Range and Selection objects are easy to grasp, and then you’ll need no recipes to make them do what you want.
Range
The basic concept of selection is Range, that is essentially a pair of “boundary points”: range start and range end.
A Range object is created without parameters:
let range = new Range();
Then we can set the selection boundaries using range.setStart(node, offset) and range.setEnd(node, offset).
As you might guess, further we’ll use the Range objects for selection, but first let’s create few such objects.
Selecting the text partially
The interesting thing is that the first argument node in both methods can be either a text node or an element node, and the meaning of the second argument depends on that.
If node is a text node, then offset must be the position in its text.
For example, given the element <p>Hello</p>, we can create the range containing the letters “ll” as follows:
<p id="p">Hello</p>
<script>
let range = new Range();
range.setStart(p.firstChild, 2);
range.setEnd(p.firstChild, 4);
// toString of a range returns its content as text
console.log(range); // ll
</script>
Here we take the first child of <p> (that’s the text node) and specify the text positions inside it:
Selecting element nodes
Alternatively, if node is an element node, then offset must be the child number.
That’s handy for making ranges that contain nodes as a whole, not stop somewhere inside their text.
For example, we have a more complex document fragment:
<p id="p">Example: <i>italic</i> and <b>bold</b></p>
Here’s its DOM structure with both element and text nodes:
Let’s make a range for "Example: <i>italic</i>".
As we can see, this phrase consists of exactly two children of <p>, with indexes 0 and 1:
-
The starting point has
<p>as the parentnode, and0as the offset.So we can set it as
range.setStart(p, 0). -
The ending point also has
<p>as the parentnode, but2as the offset (it specifies the range up to, but not includingoffset).So we can set it as
range.setEnd(p, 2).
Here’s the demo. If you run it, you can see that the text gets selected:
<p id="p">Example: <i>italic</i> and <b>bold</b></p>
<script>
let range = new Range();
range.setStart(p, 0);
range.setEnd(p, 2);
// toString of a range returns its content as text, without tags
console.log(range); // Example: italic
// apply this range for document selection (explained later below)
document.getSelection().addRange(range);
</script>
Here’s a more flexible test stand where you can set range start/end numbers and explore other variants:
<p id="p">Example: <i>italic</i> and <b>bold</b></p>
From <input id="start" type="number" value=1> – To <input id="end" type="number" value=4>
<button id="button">Click to select</button>
<script>
button.onclick = () => {
let range = new Range();
range.setStart(p, start.value);
range.setEnd(p, end.value);
// apply the selection, explained later below
document.getSelection().removeAllRanges();
document.getSelection().addRange(range);
};
</script>
E.g. selecting in the same <p> from offset 1 to 4 gives us the range <i>italic</i> and <b>bold</b>:
We don’t have to use the same node in setStart and setEnd. A range may span across many unrelated nodes. It’s only important that the end is after the start in the document.
Selecting a bigger fragment
Let’s make a bigger selection in our example, like this:
We already know how to do that. We just need to set the start and the end as a relative offset in text nodes.
We need to create a range, that:
- starts from position 2 in
<p>first child (taking all but two first letters of "Example: ") - ends at the position 3 in
<b>first child (taking first three letters of “bold”, but no more):
<p id="p">Example: <i>italic</i> and <b>bold</b></p>
<script>
let range = new Range();
range.setStart(p.firstChild, 2);
range.setEnd(p.querySelector('b').firstChild, 3);
console.log(range); // ample: italic and bol
// use this range for selection (explained later)
window.getSelection().addRange(range);
</script>
As you can see, it’s fairly easy to make a range of whatever we want.
If we’d like to take nodes as a whole, we can pass elements in setStart/setEnd. Otherwise, we can work on the text level.
Range properties
The range object that we created in the example above has following properties:
startContainer,startOffset– node and offset of the start,- in the example above: first text node inside
<p>and2.
- in the example above: first text node inside
endContainer,endOffset– node and offset of the end,- in the example above: first text node inside
<b>and3.
- in the example above: first text node inside
collapsed– boolean,trueif the range starts and ends on the same point (so there’s no content inside the range),- in the example above:
false
- in the example above:
commonAncestorContainer– the nearest common ancestor of all nodes within the range,- in the example above:
<p>
- in the example above:
Range selection methods
There are many convenience methods to manipulate ranges.
We’ve already seen setStart and setEnd, here are other similar methods.
Set range start:
setStart(node, offset)set start at: positionoffsetinnodesetStartBefore(node)set start at: right beforenodesetStartAfter(node)set start at: right afternode
Set range end (similar methods):