javascript エラー「Uncaught TypeError: Cannot create property ‘xxx’ on string ‘xxx’」の解決方法

javascript エラー「Uncaught TypeError: Cannot create property ‘xxx’ on string ‘xxx’」の解決方法

javascriptで、エラー「Uncaught TypeError: Cannot create property ‘xxx’ on string ‘xxx’」が発生した場合の原因と解決方法を記述してます。「use strict」を使用した厳格モード時だけ発生します。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 108.0.5359.72

エラー内容

以下のコードでボタンクリック時に発生。

<input id="txt" type="text" value="foo">
<p id="foo"></p>
<input id="btn" type="button" value="ボタン" />

<script>

'use strict';

function hoge(){

  let bar = txt.value;
  bar.innerHTML = "test";

}

document.getElementById('btn').addEventListener('click', hoge, false);

</script>

エラーメッセージ
※このエラーは「use strict」を使用した厳格モードのみで発生します。

Uncaught TypeError: Cannot create property 'innerHTML' on string 'foo'

画像

firefox(バージョン107)では、以下のエラーとなります。

Uncaught TypeError: can't assign to property "innerHTML" on "foo": not an object

画像

原因

「innerHTML」を、要素ではなく値から作成しようとしているため

解決方法

「document.getElementById」を使用して要素から作成する

'use strict';

function hoge(){

  let bar = txt.value;
  document.getElementById(bar).innerHTML = "test";

}

document.getElementById('btn').addEventListener('click', hoge, false);

実行結果