javascript エラー「Uncaught SyntaxError: Strict mode code may not include a with statement」の解決方法

javascript エラー「Uncaught SyntaxError: Strict mode code may not include a with statement」の解決方法

javascriptで、エラー「Uncaught SyntaxError: Strict mode code may not include a with statement」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

エラー内容

以下のコードで発生。

'use strict';

with (document.getElementById('hoge')) {

  textContent = "mebee";
  style.color = "#555";

}

エラーメッセージ

Uncaught SyntaxError: Strict mode code may not include a with statement

画像

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

Uncaught SyntaxError: strict mode code may not contain 'with' statements

画像

原因

withは、非推奨となっており「use strict」を使用するとエラーとなります。

解決方法

以下のコードのように記述する

'use strict';

let elm = document.getElementById('hoge');

elm.textContent = "mebee";
elm.style.color = "#555";