본 튜토리얼은 전 세계 사람들이 이용할 수 있는 오픈 소스 프로젝트입니다. 프로젝트 페이지에 방문하셔서 번역을 도와주세요.

In this chapter we’ll cover selection in the document, as well as selection in form fields, such as <input>.

JavaScript can get the existing selection, select/deselect both as a whole or partially, remove the selected part from the document, wrap it into a tag, and so on.

You can get ready to use recipes at the end, in “Summary” section. But you’ll get much more if you read the whole chapter. 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: basically, a pair of “boundary points”: range start and range end.

Each point represented as a parent DOM node with the relative offset from its start. If the parent node is an element node, then the offset is a child number, for a text node it’s the position in the text. Examples to follow.

Let’s select something.

First, we can create a range (the constructor has no parameters):

let range = new Range();

Then we can set the selection boundaries using range.setStart(node, offset) and range.setEnd(node, offset).

For example, consider this fragment of HTML:

<p id="p">Example: <i>italic</i> and <b>bold</b></p>

Here’s its DOM structure, note that here text nodes are important for us:

Let’s select "Example: <i>italic</i>". That’s two first children of <p> (counting text nodes):

<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)
  alert(range); // Example: italic

  // apply this range for document selection (explained later)
  document.getSelection().addRange(range);
</script>
  • range.setStart(p, 0) – sets the start at the 0th child of <p> (that’s the text node "Example: ").
  • range.setEnd(p, 2) – spans the range up to (but not including) 2nd child of <p> (that’s the text node " and ", but as the end is not included, so the last selected node is <i>).

Here’s a more flexible test stand where you try more variants: