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>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● | ● | ● | ● | 確認中 | ● | ● | ● |
関連記事
- Selection.selectAllChildren()
- selectAllChildren()は、Selectionのメソッドです。あるノードの内側を選択範囲にセットします。
- Range()
- Range()は、Rangeのコンストラクタです。新しいオブジェクトを作成します。
- UIEvent()
- UIEvent()は、UIEventのコンストラクタです。新しいオブジェクトを作成します。
- DragEvent()
- DragEvent()は、DragEventのコンストラクタです。新しいオブジェクトを作成します。