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

Selection.containsNode() - ノードを含むか確認する

containsNode()は、Selectionのメソッドです。選択範囲があるノードを含んでいるか否かを確認します。

概要

名前
containsNode
所属
Selection
IDL
boolean containsNode(Node node, optional boolean allowPartialContainment = false);
仕様書
http://w3c.github.io/selection-api/#dom-selection-containsnode

説明

第1引数(node)には、対象のノードを指定します。

第2引数(allowPartialContainment)には、判定方法を真偽値で指定します。初期値はfalseです。

true
ノードの一部が、選択範囲に含まれている場合にtrue、違うならfalseを返す。
false
ノードの全体が、選択範囲に含まれている場合にtrue、違うならfalseを返す。

デモ

Selection.containsNode()のデモです。赤文字部分のspan要素が選択範囲に含まれているか否かを確認します。

<!-- このコードは編集できます。 -->

<!DOCTYPE html>
<head>
<style>
body { word-break: break-all ; tab-size: 2 ; }
div#result { white-space: pre-wrap ; }
span#hoge { color: red ; }
</style>
</head>
<body>
<p>1234567890<span id="hoge">あいうえお</span>かきくけこ</p>
<hr>
<div id="result"></div>
<script>
var selection = getSelection() ;
var element = document.getElementById( "hoge" ) ;

document.onselectionchange = function() {
	var returnValue1 = selection.containsNode( element, true ) ;
	var returnValue2 = selection.containsNode( element, false ) ;
	getSelectionInfo() ;
	appendText( "containsNode( element, true ): " + returnValue1 + "\n" ) ;
	appendText( "containsNode( element, false ): " + returnValue2 + "\n" ) ;
}

function getSelectionInfo() {
	document.getElementById( "result" ).textContent = "" ;

	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" ) ;
}

function appendText ( text ) {
	document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>

サポート状況

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