forEach를 쓰면 화살표함수를 통해 더 짧게 작성가능하지만 ie는 지원을 하지 않기에 for문을 이용해서 만들어보자!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
ul {
list-style: none;
}
.button_wrap button {
outline: none;
border: none;
background-color: lightgray;
color: white;
padding: 1rem 2rem;
cursor: pointer;
}
.button_wrap .on {
background-color: green;
}
</style>
</head>
<body>
<section class="button_wrap">
<button class="on" data-id="1">1번버튼</button>
<button data-id="2">2번버튼</button>
<button data-id="3">3번버튼</button>
</section>
<section class="contents">
<ul>
<li id="1">
<p>1번 내용입니다.</p>
</li>
<li id="2" style="display:none">
<p>2번 내용입니다.</p>
</li>
<li id="3" style="display:none">
<p>3번 내용입니다.</p>
</li>
</ul>
</section>
<script>
const btn = document.querySelectorAll('.button_wrap button');
const content = document.querySelectorAll('.contents li');
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function (e) {
e.preventDefault();
let target = e.target.dataset.id
console.log(target);
for (var x = 0; x < content.length; x++) {
content[x].style.display = 'none';
}
document.getElementById(target).style.display = 'block';
for (var j = 0; j < btn.length; j++) {
btn[j].classList.remove('on');
e.target.classList.add('on');
}
})
}
</script>
</body>
</html>코드를 입력하세요