javascript エラー「Uncaught TypeError: Failed to execute ‘setAttribute’ on ‘Element’: 2 arguments required, but only 1 present.」の解決方法

javascript エラー「Uncaught TypeError: Failed to execute ‘setAttribute’ on ‘Element’: 2 arguments required, but only 1 present.」の解決方法

javascriptで、エラー「Uncaught TypeError: Failed to execute ‘setAttribute’ on ‘Element’: 2 arguments required, but only 1 present.」が発生した場合の原因と解決方法を記述してます。

環境

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

エラー内容

以下の、「setAttribute」を使用して「disabled」に要素を変更するコードを実行した際に発生。

<input id="txt" type="text"/>

<script>

const elm = document.getElementById('txt');

if(elm !== null){

    elm.setAttribute("disabled");

}

</script>

エラーメッセージ

Uncaught TypeError: Failed to execute 'setAttribute' on 'Element': 2 arguments required, but only 1 present.

画像

firefox102の場合は、以下のエラーが発生します。

Uncaught TypeError: Element.setAttribute: At least 2 arguments required, but only 1 passed

画像

safari15.5では、以下のエラーとなります。

TypeError: Not enough arguments

画像

原因

「setAttribute」使用時は、第二引数に値を指定する必要があるため

要素名.setAttribute(名前,値);

解決方法

「値」を指定する

<input id="txt" type="text"/>

<script>

const elm = document.getElementById('txt');

if(elm !== null){

    elm.setAttribute("disabled", true);

}

</script>

実行結果

ちなみに「setAttribute」を使用しないで「要素名.disabled」を使用する方法もあります。

const elm = document.getElementById('txt');

if(elm !== null){

    elm.disabled = true;

}