aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/api/abstractrange/index.html
blob: 8a466636431a5b18523770c530b6b03811f695da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
---
title: AbstractRange
slug: Web/API/AbstractRange
tags:
  - API
  - Abstract
  - Abstract Interface
  - AbstractRange
  - DOM
  - DOM API
  - Interface
  - NeedsTranslation
  - Range
  - Reference
  - TopicStub
translation_of: Web/API/AbstractRange
---
<div>{{APIRef("DOM WHATWG")}}</div>

<p><span class="seoSummary">The <strong><code>AbstractRange</code></strong> abstract interface is the base class upon which all {{Glossary("DOM")}} range types are defined. A <strong>range</strong> is an object that indicates the start and end points of a section of content within the document.</span></p>

<p>As an abstract interface, you will not directly instantiate an object of type <code>AbstractRange</code>. Instead, you will use the {{domxref("Range")}} or {{domxref("StaticRange")}} interfaces. To understand the difference between those two interfaces, and how to choose which is appropriate for your needs.</p>

<p>{{InheritanceDiagram}}</p>

<h2 id="Properties">Properties</h2>

<dl>
 <dt>{{domxref("AbstractRange.collapsed", "collapsed")}} {{ReadOnlyInline}}</dt>
 <dd>A Boolean value which is <code>true</code> if the range is <strong>collapsed</strong>. A collapsed range is one whose start position and end position are the same, resulting in a zero-character-long range.</dd>
 <dt>{{domxref("AbstractRange.endContainer", "endContainer")}} {{ReadOnlyInline}}</dt>
 <dd>The DOM {{domxref("Node")}} in which the end of the range, as specified by the <code>endOffset</code> property, is located.</dd>
 <dt>{{domxref("AbstractRange.endOffset", "endOffset")}} {{ReadOnlyInline}}</dt>
 <dd>An integer value indicating the offset, in characters, from the beginning of the node's contents to the beginning of the range represented by the range object. This value must be less than the length of the <code>endContainer</code> node.</dd>
 <dt>{{domxref("AbstractRange.startContainer", "startContainer")}} {{ReadOnlyInline}}</dt>
 <dd>The DOM {{domxref("Node")}} in which the beginning of the range, as specified by the <code>startOffset</code> property, is located.</dd>
 <dt>{{domxref("AbstractRange.startOffset", "startOffset")}} {{ReadOnlyInline}}</dt>
 <dd>An integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the contents referred to  by the range object. This value must be less than the length of the node indicated in <code>startContainer</code>.</dd>
</dl>

<h2 id="Methods">Methods</h2>

<p><em>The <code>AbstractRange</code> interface offers no methods.</em></p>

<h2 id="Usage_notes">Usage notes</h2>

<h3 id="Range_types">Range types</h3>

<p>All ranges of content within a {{domxref("Document", "document")}} are described using instances of interfaces based on <code>AbstractRange</code>. There are two such interfaces:</p>

<dl>
 <dt>{{domxref("Range")}}</dt>
 <dd>The <code>Range</code> interface has been around for a long time and has only recently been redefined to be based upon <code>AbstractRange</code> as the need arose to define other forms of range data. <code>Range</code> provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect intersections beween ranges, and so forth.</dd>
 <dt>{{domxref("StaticRange")}}</dt>
 <dd><code>StaticRange</code> is a basic range which cannot be changed once it's been created. Specifically, as the node tree mutates and changes, the range does not. This is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex {{domxref("Range")}} interface.</dd>
</dl>

<h3 id="Contents_of_elements">Contents of elements</h3>

<p>When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element:</p>

<pre class="brush: js notranslate">let startElem = document.querySelector("p");
let endElem = startElem.querySelector("span");
let range = document.createRange();

range.setStart(startElem, 0);
range.setEnd(endElem, endElem.childNodes[0].length/2);
let contents = range.cloneContents();

document.body.appendChild(contents);
</pre>

<p>This example creates a new range, <code>rng</code>, and sets its starting point to the third child node of the first element whose class is <code>elementclass</code>. The end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range.</p>

<h3 id="Ranges_and_the_hierarchy_of_the_DOM">Ranges and the hierarchy of the DOM</h3>

<p>In order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the DOM, you can't simply specify the offset to the first and last characters in the {{Glossary("HTML")}}. There are a few good reasons for that.</p>

<p>First, after your page is loaded, the browser simply isn't thinking in terms of HTML. Once it's been loaded, the page is a tree of DOM {{domxref("Node")}} objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes.</p>

<p>Second, in order to support the mutability of the DOM tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than simply global positions within the entire document. By defining points within the document as offsets within a given node, those positions remain consistent with the content even as nodes are added to, removed from, or moved around within the DOM tree—within reason. There are fairly obvious limitations (such as if a node is moved to be after the endpoint of a range, or if the content of a node is heavily altered), but it's far better than nothing.</p>

<p>Third, using node-relative positions to define the start and end positions will generally be easier to make perform well. Rather than having to negotiate the DOM figuring out what your global offset refers to, the {{Glossary("user agent")}} (browser) can instead go directly to the node indicated by the starting position and start from there, working its way forward until it reaches the given offset into the ending node.</p>

<p>To illustrate this, consider the HTML below:</p>

<pre class="brush: html notranslate">&lt;div class="container"&gt;
  &lt;div class="header"&gt;
    &lt;img src="" class="sitelogo"&gt;
    &lt;h1&gt;The Ultimate Website&lt;/h1&gt;
  &lt;/div&gt;
  &lt;article&gt;
    &lt;section class="entry" id="entry1"&gt;
      &lt;h2&gt;Section 1: An interesting thing...&lt;/h2&gt;
      &lt;p&gt;A &lt;em&gt;very&lt;/em&gt; interesting thing happened on the way to the forum...&lt;/p&gt;
      &lt;aside class="callout"&gt;
        &lt;h2&gt;Aside&lt;/h2&gt;
        &lt;p&gt;An interesting aside to share with you...&lt;/p&gt;
      &lt;/aside&gt;
    &lt;/section&gt;
  &lt;/article&gt;
  &lt;pre id="log"&gt;&lt;/pre&gt;
&lt;/div&gt;</pre>

<p>After loading the HTML and constructing the DOM representation of the document, the resulting DOM tree looks like this:</p>

<p><a href="https://mdn.mozillademos.org/files/16886/SimpleDOM.svg"><img alt="Diagram of the DOM for a simple web page" src="https://mdn.mozillademos.org/files/16887/SimpleDOM.svg" style="height: 683px; width: 640px;"></a></p>

<p>In this diagram, the nodes representing HTML elements are shown in green. Eah row beneath them shows the next layer of depth into the DOM tree. Blue nodes are text nodes, containing the text that gets shown onscreen. Each element's contents are linked below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes.</p>

<p>If you want to create a range that incorporates the contents of the {{HTMLElement("p")}} element whose contents are <code>"A &lt;em&gt;very&lt;/em&gt; interesting thing happened on the way to the forum..."</code>, you can do so like this:</p>

<pre class="brush: js notranslate">let pRange = document.createRange();
pRange.selectNodeContents(document.querySelector("#entry1 p"));
</pre>

<p>Since we wish to select the entire contents of the <code>&lt;p&gt;</code> element, including its descendants, this works perfectly.</p>

<p>If we wish to instead copy the text "An interesting thing..." from the {{HTMLElement("section")}}'s heading (an {{HTMLElement("h2")}} element) through the end of the letters "ve" in the {{HTMLElement("em")}} within the paragraph below it, the following code would work:</p>

<pre class="brush: html notranslate">let r = document.createRange();
let startNode = document.querySelector("section h2").childNodes[0];
r.setStart(startNode, 11);

let endNode = document.querySelector("#entry1 p em").childNodes[0];
r.setEnd(endNode, 2);

let fragment = r.cloneContents();
</pre>

<p>Here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the DOM hierarchy, and then only part of one of them. What should the result look like?</p>

<p>As it turns out, the DOM specification fortunately addresses this exact issue. For example, in this case, we're calling {{domxref("Range.cloneContents", "cloneContents()")}} on the range to create a new {{domxref("DocumentFragment")}} object providing a DOM subtree which replicates the contents of the specfied range. To do this, <code>cloneContents()</code> constructs all the nodes needed to preserve the structure of the indicated range, but no more than necessary.</p>

<p>In this example, the start of the specified range is found within the text node below the section's heading, which means that the new <code>DocumentFragment</code> will need to contain an {{HTMLElement("h2")}} and, below it, a text node.</p>

<p>The range's end is located below the {{domxref("p")}} element, so that will be needed within the new fragment. So will the text node containing the word "A", since that's included in the range. Finally, an <code>&lt;em&gt;</code> and a text node below it will be added below the <code>&lt;p&gt;</code> as well.</p>

<p>The contents of the text nodes are then determined by the offsets into those text nodes given when calling {{domxref("Range.setStart", "setStart()")}} and {{domxref("Range.setEnd", "setEnd()")}}. Given the offset of 11 into the heading's text, that node will contain "An interesting thing...". Similarly, the last text node will contain simply "ve", given the request for the first two characters of the ending node.</p>

<p>The resulting document fragment looks like this:</p>

<p><img alt="A DocumentFragment representing the cloned content" src="https://mdn.mozillademos.org/files/16891/dom-fragment.svg" style="height: 319px; width: 463px;"></p>

<p>Notice especially that the contents of this fragment are all <em>below</em> the shared common parent of the topmost nodes within it. The parent <code>&lt;section&gt;</code> is not needed to replicate the cloned content, so it is isn't included.</p>

<h2 id="Example">Example</h2>

<p>Consider this simple HTML fragment of HTML.</p>

<pre class="brush: html notranslate">&lt;p&gt;&lt;strong&gt;This&lt;/strong&gt; is a paragraph.&lt;/p&gt;</pre>

<p id="JavaScript">Imagine using a {{domxref("Range")}} to extract the word "paragraph" from this. The code to do that looks like the following:</p>

<pre class="brush: js notranslate">let paraNode = document.querySelector("p");
let paraTextNode = paraNode.childNodes[1];

let range = document.createRange();
range.setStart(paraTextNode, 6);
range.setEnd(paraTextNode, paraTextNode.length-1);

let fragment = range.cloneContents();
document.body.appendChild(fragment);
</pre>

<p>First we get references to the paragraph node itelf as well as to the <em>second</em> child node within the paragraph. The first child is the {{HTMLElement("strong")}} element. The second child is the text node " is a paragraph.".</p>

<p>With the text node reference in hand, we create a new <code>Range</code> object by calling {{domxref("Document.createRange", "createRange()")}} on the <code>Document</code> itself. We set the starting position of the range to the sixth character of the text node's string, and the end position to the length of the text node's string minus one. This sets the range to encompass the word "paragraph".</p>

<p>We then finish up by calling {{domxref("Range.cloneContents", "cloneContents()")}} on the <code>Range</code> to create a new {{domxref("DocumentFragment")}} object which contains the portion of the document encompassed by the range. After that, we use {{domxref("Node.appendChild", "appendChild()")}} to add that fragment at the end of the document's body, as obtained from {{domxref("document.body")}}.</p>

<p>The result looks like this:</p>

<p>{{EmbedLiveSample("Example", 600, 80)}}</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('DOM WHATWG', '#abstractrange', 'AbstractRange')}}</td>
   <td>{{Spec2('DOM WHATWG')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>

<p>{{Compat("api.AbstractRange")}}</p>