[Javascript] forEach문을 이용한 탭 메뉴 구현하기

seoyeon·2023년 9월 21일
3

실무에 적용해보자!

목록 보기
14/15
post-thumbnail

지난시간에 이은 forEach문으로 탭 구현하기

HTML

<div class="tab-wrap">
  <button class="active">첫번째 탭</button>
  <button>두번째 탭</button>
  <button>세번째 탭</button>
</div>
<div class="tab-container">
  <div class="active">
    <p>첫번째 탭 내용입니다.</p>
  </div>
    <div>
    <p>두번째 탭 내용입니다.</p>
  </div>
    <div>
    <p>세번째 탭 내용입니다.</p>
  </div>
</div>

CSS

.tab-wrap { 
  display: flex;
  gap: 12px;
  margin-bottom: 10px;
}
.tab-wrap button {
  cursor: pointer;
}
.tab-wrap button.active {
  background-color: cornflowerblue;
}
.tab-container > div {
  display: none;
  width: 200px;
  height: 200px;
  line-height: 190px;
  background-color: #eee;
  text-align: center;
}
.tab-container > div.active {
  display: block;
}

JavaScript

const tabBtns = document.querySelectorAll('.tab-wrap > button');
const tabConts = document.querySelectorAll('.tab-container > div');

tabBtns.forEach((btn, index) => {
  btn.addEventListener('click', () => {
    tabBtns.forEach(otherBtn => {
      otherBtn.classList.remove('active');
    });
    tabConts.forEach(othercont => {
      othercont.classList.remove('active');
    });
    tabBtns[index].classList.add('active');
    tabConts[index].classList.add('active');
  });
});

결과

0개의 댓글