SYNCERのロゴ
アイキャッチ画像

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>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年10月16日 (月)
コンテンツを公開しました。