Selection.getRangeAt() - 範囲を取得する
getRangeAt()は、Selectionのメソッドです。インデックス番号を指定して、選択範囲を表すRangeを取得します。飛び飛びで複数の箇所を選択しない限り、Selectionには1つの範囲しか含まれていません。
概要
- 名前
- getRangeAt
- 所属
- Selection
- IDL
Range getRangeAt(unsigned long index);
- 仕様書
- http://w3c.github.io/selection-api/#dom-selection-getrangeat
説明
引数(index)には、インデックス番号を指定する。
デモ
Selection.getRangeAt()のデモです。1つ目(インデックス番号0)の範囲を取得しています。
<!-- このコードは編集できます。 -->
<!DOCTYPE html>
<head>
<style>
body { word-break: break-all ; tab-size: 2 ; }
div#result { white-space: pre-wrap ; }
</style>
</head>
<body>
<p>1234567890<br>あいうえおかきくけこ<br>abcdefghij<br>ABCDEFGHIJ</p>
<hr>
<div id="result"></div>
<script>
document.onselectionchange = function () {
document.getElementById( "result" ).textContent = "" ;
var selection = getSelection() ;
console.log( selection ) ;
appendText( selection + "\n\n" ) ;
appendText( "anchorNode: " + selection.anchorNode + " " + selection.anchorNode.data + "\n" ) ;
appendText( "anchorOffset: " + selection.anchorOffset + "\n" ) ;
appendText( "focusNode: " + selection.focusNode + " " + selection.focusNode.data + "\n" ) ;
appendText( "focusOffset: " + selection.focusOffset + "\n" ) ;
appendText( "isCollapsed: " + selection.isCollapsed + "\n" ) ;
appendText( "rangeCount: " + selection.rangeCount + "\n" ) ;
appendText( "type: " + selection.type + "\n\n" ) ;
var range = selection.getRangeAt(0) ;
appendText( "getRangeAt(0): " + range + "\n" ) ;
appendText( "\t" + "startContainer: " + range.startContainer + "\n" ) ;
appendText( "\t" + "startContainer.data: " + range.startContainer.data + "\n" ) ;
appendText( "\t" + "startOffset: " + range.startOffset + "\n" ) ;
appendText( "\t" + "endContainer: " + range.endContainer + "\n" ) ;
appendText( "\t" + "endContainer.data: " + range.endContainer.data + "\n" ) ;
appendText( "\t" + "endOffset: " + range.endOffset + "\n" ) ;
appendText( "\t" + "collapsed: " + range.collapsed + "\n" ) ;
appendText( "\t" + "commonAncestorContainer: " + range.commonAncestorContainer + "\n" ) ;
appendText( "\t" + "commonAncestorContainer.data: " + range.commonAncestorContainer.data + "\n" ) ;
}
function appendText ( text ) {
document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● | ● | ● | ● | ● | ● | ● | ● |
関連記事
- Selection.addRange()
- addRange()は、Selectionのメソッドです。Rangeを指定して選択範囲をセットします。既に選択範囲が存在する場合、無視されます。
- Selection.containsNode()
- containsNode()は、Selectionのメソッドです。選択範囲があるノードを含んでいるか否かを確認します。
- Selection.focusOffset
- focusOffsetは、Selectionのプロパティです。選択範囲の終点の位置を返します。
- Range()
- Range()は、Rangeのコンストラクタです。新しいオブジェクトを作成します。