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

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

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>