script.js:16 Uncaught TypeError: colorsBtn.addEventListener is not a function
at script.js:16:15
at Array.forEach (<anonymous>)
at script.js:14:8
const redBtn = document.querySelector("#red-btn");
const greenBtn = document.querySelector("#green-btn")
const blueBtn = document.querySelector("#blue-btn")
const resetBtn = document.querySelector("#reset-btn")
const backgroundColor = document.querySelector("#background-color")
resetBtn.addEventListener('click', () => {
console.log("초기화");
backgroundColor.style.backgroundColor="white";
})
const colors = ['red', 'green', 'blue'];
let colorsBtn = "";
colors.forEach((element) => {
console.log("엘리먼트 : ", element);
colorsBtn = element + "Btn";
console.log("컬러체인저버튼", colorsBtn);
colorsBtn.addEventListener('click',()=>{backgroundColor.style.backgroundColor=element})
});
위 코드는 기존에 짯던 코드 문제점 : colorBtn.addEventListener : string 즉 문자열은 DOM 요소가 아님, 이벤트리스너 사용 불가
능.
const resetBtn = document.querySelector("#reset-btn")
const backgroundColor = document.querySelector("#background-color")
resetBtn.addEventListener('click', () => {
console.log("초기화");
backgroundColor.style.backgroundColor="white";
})
const colors = ['red', 'green', 'blue'];
colors.forEach((element) => {
const btn = document.querySelector(`#${element}-btn`)
btn.addEventListener('click', () => {
backgroundColor.style.backgroundColor=element;
})
});
바뀐 코드 : 색 버튼을 셀렉트 하는 것을 forEach를 사용해 하나로 바인딩해 노가다성 코드를 제거했음.
네, 중복되는 부분을 없애고 이벤트 위임(event delegation)을 쓰면 훨씬 간결하게 쓸 수 있습니다. 예를 들어 버튼들을 한 컨테이너로 묶고, 클릭된 버튼의 id를 보고 색상을 바꾸도록 하면 됩니다:
const backgroundColor = document.querySelector("#background-color");
const wrapper = document.querySelector(".button-wrapper");
wrapper.addEventListener("click", (e) => {
// 버튼인지 확인
if (e.target.tagName !== "BUTTON") return;
// 초기화 버튼이면 흰색으로
if (e.target.id === "reset-btn") {
backgroundColor.style.backgroundColor = "white";
return;
}
// id가 "red-btn" → "red" 추출
const color = e.target.id.replace("-btn", "");
backgroundColor.style.backgroundColor = color;
});
const wrapper = document.querySelector(".button-wrapper");
wrapper.addEventListener("click", (e) => {
// 버튼인지 확인
if (e.target.tagName !== "BUTTON") return;
// 초기화 버튼이면 흰색으로
if (e.target.id === "reset-btn") {
backgroundColor.style.backgroundColor = "white";
return;
}
// id가 "red-btn" → "red" 추출
const color = e.target.id.replace("-btn", "");
backgroundColor.style.backgroundColor = color;
});
이렇게 하면 모든 버튼에 일일이 addEventListener를 붙이지 않고, 한 번의 리스너로 처리할 수 있습니다.
📌 장점
- 버튼이 늘어나도 코드 수정 최소화
- 리스너 등록 한 번 → 메모리 사용 적음
- 유지보수가 쉬움
chatGPT 에게 코드 줄이는 법 질문 그리고 그것에 대한 답변.