LoginSignup
42
29

More than 3 years have passed since last update.

getElementsByClassNameの結果に対してforEachやmapを使う方法

Last updated at Posted at 2018-09-15

まずgetElementsByClassNameでHTMLCollectionを取得します

var elements = document.getElementsByClassName( "sample" );

HTMLCollectionに対してforEachを使うと

elements.forEach(x => console.log(x)); // Uncaught TypeError

Uncaught TypeError: elements.forEach is not a function というエラーが発生します。

HTMLCollectionは配列ではないので、forEachやmapは利用できないらしいです。

forEachやmapを使いたかったので配列に変換します。

elements = Array.from( elements ) ;

これで配列に変換できたのでforEachやmapなどが使えるようになりました。

elements.forEach(x => console.log(x));
42
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
29