The createRange Method
The createRange method - creates a
document fragment object. This fragment can
contain element fragments and text sections.
See examples to understand the essence of this method.
Syntax
document.createRange();
Example
Get the paragraph content:
<p id="p">
<b>abcde</b>fg
</p>
let p = document.getElementById('p');
let text = document.createRange();
text.selectNode(p);
alert(text.toString());
Code execution result:
'abcdefg'
Example
But this way you can get not only the content of an element, but generally any part of the document. Even if it starts in one element and ends in another:
<div id="root">
<p>
text1
</p>
<p>
text2
</p>
</div>
let root = document.getElementById('root');
let start = root.children[0].firstChild;
let end = root.children[1].firstChild;
let text = document.createRange();
text.setStart(start, 12);
text.setEnd(end, 8);
alert(text.toString());
See Also
-
method
getSelection