素肌にサスペンダー

個人的な備忘と日記

【JavaScript】特定のDOM内のgetElementsByNameは取得出来ない

getElementsByNameを使うと、name属性から要素を指定出来る。

document.getElementsByName('input-name')とすると、ページ内の全てのinput-nameというname属性を持つ要素全て取得できる。

例えばformが複数ある中で、特定のformのinput-nameというname属性を持つ要素を取得したい場合に、document.getElementById('特定のformのID')でDOMを指定してから、その中でdocument.getElementsByName('input-name')すると、以下のエラーになった。

Uncaught TypeError: testB.getElementsByName is not a function

querySelectorAllを使って、querySelectorAll('input[name="input-name"]')と書けば、意図したものが取得できた。

サンプル

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
</head>
<body>
    <form id="test-a">
        <input type="text" name="input-name">
    </form>
    <form id="test-b">
        <input type="text" name="input-name">
    </form>
    <script>
       window.onload = function () {
           /* test-b内のinput name="input-name"を取得したい */

           const testB = document.getElementById('test-b')
           // ▼ 取得できない
           // const name = testB.getElementsByName('input-name')

           // ▼ ページ内全部が対象なので、test-aのも取得してしまう
           // const name = document.getElementsByName('input-name')

           // ▼ test-b内のinput-nameのみ取得できる
           const name = testB.querySelectorAll('input[name="input-name"]')
           console.log(name)
       }
   </script>
</body>
</html>