1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

getElementsByClassName()で取得した要素を配列のように扱う方法

1
Posted at

問題

getElementsByClassName()はHTMLCollection()が返却されるのでforEach()が使えませんでした。


const elements = document.getElementsByClassName('xxx');
console.log(elements) //HTMLCollection()

elements.forEach((e) => {}) // TypeError: elements.forEach is not a function

解決法

HTMLCollection()をなんとか配列にしてやればOKです。

Array.form()


const elements = Array.from(document.getElementsByClassName('xxx'));
console.log(elements) //[]

elements.forEach((e) => {}) // OK

[].slice.call()


const elements = [].slice.call(document.getElementsByClassName('xxx'));
console.log(elements) //[]

elements.forEach((e) => {}) // OK
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?