일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- @font-face
- label 태그
- border:none;
- label
- doctype
- border:0;
- html #display #block #inline
- border
- 인터랙티브 웹 클론 #BBC 코로나19가 바꿀 사무실의 미래 #1분코딩
- javacript #javasript 객체 #객체 #배열
- 시멘틱 태그 #시멘틱 레이아웃
- html #fontawesome #폰트어썸
- Today
- Total
yeji
복수 선택 메소드와 addEventListener 본문
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 |