LoginSignup
25
11

More than 3 years have passed since last update.

HTMLCollectionにはforEachが無い

Posted at

JavaScriptからHTML要素を扱うとき、要素の配列を受け取るとHTMLCollectionという型になることがあります。

例えばSelectのOptionなどがそれに当たります。

<select id="select-box">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select>
const options = document.querySelector('#select-box').options;

このようにしたときにoptionsがHTMLCollectionになりますが、これは配列ではないのでforEachは使えません。

ただし、HTMLCollectionはArrayライクなObjectではあるので、以下のような方法でforEachを使うことができます。


Array.prototype.forEach.call(options, function ..)

Arrayライクなオブジェクトについてはこちら https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections

25
11
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
25
11