javascript 「Uncaught TypeError: Failed to execute ‘setStart’ on ‘Range’: parameter 1 is not of type ‘Node’.」が発生した場合の対処法
- 作成日 2021.07.14
- 更新日 2022.09.20
- javascript
- javascript

javascriptで、setStartを利用してエラー「Uncaught TypeError: Failed to execute ‘setStart’ on ‘Range’: parameter 1 is not of type ‘Node’.」が発生した場合の対処法を記述してます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 105.0.5195.127
エラー全文
以下のコードで発生。
<div>
<p id="hoge">
node0
<i>node1</i>
node2
<i>node3</i>
</p>
<input id="btn" type="button" value="ボタン" />
</div>
<script>
'use strict';
document.getElementById('btn').onclick = function () {
hoge()
}
function hoge(){
const range = new Range();
range.setStart(hoge, 0);
range.setEnd(hoge, 3);
document.getSelection().addRange(range);
}
</script>
エラー全文
Uncaught TypeError: Failed to execute 'setStart' on 'Range': parameter 1 is not of type 'Node'.
画像

firefox 102 では以下のエラーとなります。
Uncaught TypeError: Range.setStart: Argument 1 does not implement interface Node.
画像

原因
関数名「hoge」と、「id」に指定している「hoge」が重複していたため
対処法
どちらかを変更する
※ここでは関数名を「hoge」から「foo」に変更してます。
<div>
<p id="hoge">
node0
<i>node1</i>
node2
<i>node3</i>
</p>
<input id="btn" type="button" value="ボタン" />
</div>
<script>
'use strict';
document.getElementById('btn').onclick = function () {
foo()
}
function foo(){
const range = new Range();
range.setStart(hoge, 0);
range.setEnd(hoge, 3);
document.getSelection().addRange(range);
}
</script>
-
前の記事
Ruby 文字列の中で数式を利用する 2021.07.13
-
次の記事
React.js UIコンポーネント「Elementz」を使用する 2021.07.14
コメントを書く