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

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

javascriptで、エラー「Uncaught TypeError: xxx.getElementsByTagName is not a function」が発生した場合の原因と解決方法を記述してます。「HTMLCollection」に、そのまま「getElementsByTagName」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

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

エラー内容

以下の、クラス名を指定してタグ「p」の要素を取得しようとした際に発生。

<div class="box"><p>aaa</p><p>bbb</p></div>
<div class="box"><p>ccc</p></div>
<div class="box"><p>ddd</p><p>eee</p></div>

<script>

const elems = document.getElementsByClassName('box');

const result = elems.getElementsByTagName('p');

console.log(result);

</script>

エラーメッセージ

Uncaught TypeError: elems.getElementsByTagName is not a function

画像

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

Uncaught TypeError: elems.getElementsByTagName is not a function

画像

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

TypeError: elems.getElementsByTagName is not a function. (In 'elems.getElementsByTagName('p')', 'elems.getElementsByTagName' is undefined)

画像

原因

「HTMLCollection」に対して、「getElementsByTagName」を使用しているため。

<div class="box"><p>aaa</p><p>bbb</p></div>
<div class="box"><p>ccc</p></div>
<div class="box"><p>ddd</p><p>eee</p></div>

<script>

const elems = document.getElementsByClassName('box');

console.log(elems);
// HTMLCollection(3) [div.box, div.box, div.box]

const result = elems.getElementsByTagName('p');

console.log(result);

</script>

解決方法

いずれかの要素を指定して実行する場合は「インデックス番号」を指定して「DOM要素」にします。

const elems = document.getElementsByClassName('box');

console.log(elems);
// HTMLCollection(3) [div.box, div.box, div.box]

const result = elems[0].getElementsByTagName('p');

console.log(result);
// HTMLCollection(2) [p, p]

実行結果

取得した全ての要素に使用する場合は「HTMLCollection」を配列化して「forEach」などを使用します。

const elems = document.getElementsByClassName('box');

[...elems].forEach(v => {

  console.log(v.getElementsByTagName('p'));

});

実行結果

または、判定してから使用します。

const elems = document.getElementsByClassName('box');

if (typeof elems === 'object' && 'getElementsByTagName' in elems && elems !== null) {

  elems.setAttribute('id', 'foo');

};