createRangeメソッド
メソッド createRange は、文書フラグメントオブジェクトを
作成します。このフラグメントは、
要素のフラグメントやテキスト部分を含むことができます。
このメソッドの本質を理解するために例を見てください。
構文
document.createRange();
例
段落の内容を取得します:
<p id="p">
<b>abcde</b>fg
</p>
let p = document.getElementById('p');
let text = document.createRange();
text.selectNode(p);
alert(text.toString());
コード実行結果:
'abcdefg'
例
この方法では、要素の内容だけでなく、 文書の任意の部分を取得することができます。 たとえそれが一つの要素で始まり、別の要素で終わる場合でも可能です:
<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());
関連項目
-
メソッド
getSelection