getElementsByClassName와 addEventListener는 왜 같이 쓸 수 없을까?

SUM·2024년 7월 23일
0

JavaScript

목록 보기
6/6

평화롭게 todolist를 만들던 오늘 오후...
js 켜놓고 getElementsByClassName으로 class를 불러왔는데
자동완성이 안붙지 뭐야 그래서 왜 안되는지 알아봄
✅각종 오역과 의역 주의 !!!

https://stackoverflow.com/questions/56763768/is-there-any-way-to-add-an-event-listener-to-a-class

스택오버플로우의 해당 링크를 타고 들어가서 질문과 답변을 살펴보자.

대충 getElementsByClassName에 addEventListener를 쓰고 싶은데 뭔가 안된다! 는 내용의 질문이 올라와있고

그에 대한 답변을 내 맘대로 요약하면

getElementsByClassName()는 복수형 요소이면서, 배열이 아닌 node list를 return하기 때문에 배열 메소드에는 사용할 수 없다.

그렇다면 addEventListener는 배열매소드인가?
그건 아닌 것 같다. 그러면 대체 왜 안되는걸까?

이에 대한 답변은 또 구글링하다가 찾았다~!

addEventListener() adds a Listener to one element.

https://forum.freecodecamp.org/t/neede-help-with-document-getelementsbyclassname-addeventlistener/219116

The main difference between Element and Node is that Element is a specific type of Node that represents an HTML or XML element. While all Elements are Nodes, not all Nodes are Elements. Another key difference is that Elements have additional properties and methods that are specific to elements.

JavaScript HTML DOM Node Lists - W3Schools
https://www.w3schools.com › js_htmldom_nodelist

An HTMLCollection is a collection of document elements. A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number.

What Is the Difference Between Element and Node in DOM - Medium https://medium.com › front-end-weekly

element는 node이지만 모든 node가 element인 것은 아니고, element는 해당 element에 특정한 추가적인 속성과 메서드를 갖는다.

또한, NodeList는 document nodes의 모음집이니까 마찬가지로 element가 아니다!

즉, addEventListener()는 하나의 element에 listener를 추가하기 때문에 element가 아닌 NodeList에는 addEventListener가 올 수 없다~~~!

라는 게 제 구글링의 결과! 입니다!

사실 구글링은 어디까지나 구글링이고 제가 컴퓨터 관련 지식이 해박한 것도 아니고 그렇다고 영어에 능통한 것도 아니고 (...) 그래서 이게 정답이다! 라고는 절대절대로 말 못하고요. 그냥 저는 제가 납득이 안되면 이해가 어렵더라고요. 그래서 공부도 할 겸 찾아봤음.

틀릴 시 님 말이 다 맞음.
비꼬는 거 ❌ 진짜로 저는 아는 거 하나도 없어서 당신의 생각이 맞을겁니다

그러니까 뭔가 이상하다 싶으면 댓글로 알려주세요 제발요 🙏 🥺

이상입니다 그럼 안뇽...~

profile
프론트엔드 개발자가 될래요 🌟

2개의 댓글

comment-user-thumbnail
2024년 7월 23일

내가 몰랐던 점 찾아가는 능력 좋습니다~

답글 달기
comment-user-thumbnail
2024년 7월 23일

저도 궁금했던 부분이었는데 덕분에 알게 되었어요! 감사합니다!

답글 달기