-
[JS] Uncaught TypeError: forEach is not a function errorFrontEnd/JavaScript 2022. 5. 23. 01:42
Uncaught TypeError: forEach is not a function error
document.getElementsByClassName으로 얻은 배열에 forEach를 사용하려고 시도했더니 이런 에러가 발생했다.
알고보니 getElements로 받아온 DOM 배열(?)은 실제로는 배열(Array)이 아닌 HTML collection이었다.
getElementsBy~가 반환하는 값은 배열이 아니기 때문에 forEach를 사용할 수 없다.
https://developer.mozilla.org/ko/docs/Web/API/Element/getElementsByTagName
Element.getElementsByTagName() - Web API | MDN
Element.getElementsByTagName() 메서드는 제공된 태그 네임(tag name)을 가지는 엘리먼트의 유효한 HTML 컬랙션를 반환합니다. 엘리먼트가 특정된 범위를 검색하는 경우, 그 자신의 엘리먼트는 제외하고,
developer.mozilla.org
해결방법!?나는 getElements 대신 querySelectorAll을 사용했다!querySelectorAll은 NodeList (Array)를 반환하기 때문에 forEach 사용이 가능했다.https://developer.mozilla.org/ko/docs/Web/API/Document/querySelectorAllDocument.querySelectorAll() - Web API | MDN
Document 메소드 querySelectorAll() 는 지정된 셀렉터 그룹에 일치하는 다큐먼트의 엘리먼트 리스트를 나타내는 정적(살아 있지 않은) NodeList 를 반환합니다.
developer.mozilla.org
'FrontEnd > JavaScript' 카테고리의 다른 글
[JS] 비동기 처리와 Callback (0) 2022.06.17 [JS] Uncaught TypeError: Cannot read properties of null 에러 해결방법 (0) 2022.06.04 [JS] 문벅스 Vanila JS (0) 2022.05.16 [JS] innerHTML, innerText, textConten (0) 2022.05.14 [JS] Nomadcoders - Zoom Clone Coding (0) 2022.05.06