javascript エラー「Uncaught TypeError: xxx.getElementsByName is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxx.getElementsByName is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx.getElementsByName is not a function」が発生した場合の原因と解決方法を記述してます。

環境

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

エラー内容

以下の、チェックボックスから特定のform内の値のみを取得しようとしたコードを実行した際に発生。

<form id="frm_a">
    <input type="checkbox" name="foo" value="aaa">
    <input type="checkbox" name="foo" value="bbb">
</form>

<form id="frm_b">    
    <input type="checkbox" name="foo" value="ccc">
    <input type="checkbox" name="foo" value="ddd">
    <input type="checkbox" name="foo" value="eee">
</form>

<script>

const b = document.getElementById('frm_b')

const result = b.getElementsByName('foo')

for (let i = 0; i < result.length; i++) {
  console.log(result[i].value);  
}

</script>

エラーメッセージ

Uncaught TypeError: b.getElementsByName is not a function

画像

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

Uncaught TypeError: b.getElementsByName is not a function

画像

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

TypeError: b.getElementsByName is not a function. (In 'b.getElementsByName('foo')', 'b.getElementsByName' is undefined)

画像

原因

「getElementsByName」は、「id」を指定して利用することができないため

解決方法

「querySelectorAll」を使用する

<form id="frm_a">
    <input type="checkbox" name="foo" value="aaa">
    <input type="checkbox" name="foo" value="bbb">
</form>

<form id="frm_b">    
    <input type="checkbox" name="foo" value="ccc">
    <input type="checkbox" name="foo" value="ddd">
    <input type="checkbox" name="foo" value="eee">
</form>

<script>

const b = document.getElementById('frm_b')

const result = b.querySelectorAll('input[name="foo"]')

for (let i = 0; i < result.length; i++) {
  console.log(result[i].value);  
}

</script>

実行結果