JavaScript | 클릭한 요소와 나머지 요소 제어하기 with forEach

AEHEE·2023년 5월 15일
1

JavaScript

목록 보기
8/10
post-thumbnail

클릭 이벤트에서 사용자가 클릭한 요소외 나머지 것들의 클래스를 삭제해야하는 스크립트를 짰어야했다. 정말 많이 쓰는 이벤트이기에 내가 아는 방식으로 작성을 했는데 원하는 방식으로 구현이 안됨... jQuery를 이용하다가 javascript로만 짜려고 하면 가끔 머리가 복잡할 때가 있다.

jQuery를 이용할 때는 each문과 .siblings()를 이용하여 간단하게 구현할 수 있었다.
클릭한 요소의 나머지 것을 구하는 것이 아니라, 클릭 이벤트가 실행이 되면 제일 먼저 나머지 것들에게 줄 이벤트를 실행 후 선택한 요소에 이벤트를 주면 된다.

그럼 JavaScript로는 어떻게 짤 수 있을까?
아래의 DOM구조로 진행을 했다.

<div>
	<button type="button"></button>
</div>
<div>
	<button type="button"></button>
</div>
<div>
	<button type="button"></button>
</div>

👩🏻‍💻 forEach() 메서드

forEach()는 배열 메서드로서 함수를 배열 요소 각각에 대해 실행한다.
그리고 세 가지 매개변수를 받는다.

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg]
  • currentvalue는 현재 처리할 요소
  • index는 처리할 현재 요소의 인덱스
  • Array는 forEach 메서드를 호출한 배열
const numbers = [1, 2, 3, 4, 5]
numbers.forEach((number, index, array) => {
    console.log('number: ' + number + ' index: ' + index + ' array: ' + array);
});

//출력
//number: 1 index: 0 array: 1,2,3,4,5
//number: 2 index: 1 array: 1,2,3,4,5
//number: 3 index: 2 array: 1,2,3,4,5
//number: 4 index: 3 array: 1,2,3,4,5
//number: 5 index: 4 array: 1,2,3,4,5

이렇게 클릭한 현재요소를 구할 수 있다.
그럼 이제 나머지 요소를 찾아야하는데, forEach()메서드를 이용해 또 구할 수 있다.

const number = document.querySelectorAll('button');
numbers.forEach((number, index, array) => {
	number.addEventListener('click', () => {
      array.forEach((element) => console.log(element));
	);
});

여기에 찍힌 console은 전체 엘리먼트가 찍히게 되고,

const number = document.querySelectorAll('button');
numbers.forEach((number, index, array) => {
	number.addEventListener('click', () => {
      array.forEach((element) => element.parentNode.classList.remove(제어할 클래스명));
      number.parentNode.classList.add(제어할 클래스명);
	);
});

전체 엘리먼트의 부모 요소에 제어할 클래스명을 삭제하고 그 다음 선택한 요소에 이벤트를 줬다. 사실 너무 간단한 로직...ㅋㅋㅋㅋㅋㅋㅋ

근데 가끔 코드를 보다보면 생각이 막힐 때가 있다.
혹시나 해서 기록용으로 적어두는 이 글!

profile
UI개발자에서 FE개발자로 한걸음 더!

0개의 댓글

관련 채용 정보