yeji

복수 선택 메소드와 addEventListener 본문

JavaScript

복수 선택 메소드와 addEventListener

yeji717 2022. 5. 14. 01:21

querySelector getElementById VS querySelectorAll getElementsByClassName

 

노마드코더님의 강의를 듣다가 과제를 수행하던 중

getElementsByTagName('h2'); 로 이벤트를 추가했다.

그런데 title.addEventListener is not a function 이라 오류가 나왔다.

그래서 다시 querySelector('h2')로 바꾸고 해보니 다시 됐다.

 

여러 요소를 선택하는 메소드 뒤에는 addEventListener를 붙일 수 없다고 추측했다.

querySelector와 getElementById는 단일 DOM 객체를 불러오지만 복수 선택 메소드들은 NodeList를 가져오기 때문이라고 함.

 

해결방법 1)

해결방법은 NodeList의 요소 하나하나에 for문으로 접근해 이벤트리스너를 붙이기.

 

const cells = document.getElementsByClassName('cell');

for(const i=0; i<cells.length; i++) {

    const eachCell = cells[i];

 

    eachCell.addEventListener('click', function() {

       //blah blah

    });

};

 

 

해결방법 2)

forEach

document.querySelectorAll('.cell').forEach((cell) => {

    cell.addEventListenet('click', function(){

    //blah blah

    });

});

'JavaScript' 카테고리의 다른 글

IE에서 forEach 안될 때  (0) 2022.05.17
Top 버튼 만들기  (0) 2021.11.15
setTimeout, setInterval, clearInterval  (0) 2021.04.06
jQuery / width(), innerWidth(), outerWidth() 비교  (0) 2021.04.06
getBoundingClientRect()  (0) 2021.01.26
Comments