프런트엔드-자바스크립트

자바스크립트 핵심

강사: 정프런트 · 작성자: 이종춘 · 작성일: 2026-06-11 21:17:51 · 조회수: 12

문제 5 : querySelectorAll + for문 + active
목록으로
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>문제5</title>

<style>

*{
margin:0;
padding:0;
box-sizing:border-box;
}

.wrap{
width:500px;
margin:100px auto;
display:flex;
justify-content:space-between;
}

.box{
width:150px;
height:150px;
background-color:lightgray;
border-radius:10px;
cursor:pointer;

display:flex;
justify-content:center;
align-items:center;

font-size:40px;
transition:0.3s;
}

.active{
background-color:tomato;
color:white;
}

</style>
</head>
<body>

<div class="wrap">

<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>

</div>

<script>

const boxAll = document.querySelectorAll('.box');

for(let i = 0; i < boxAll.length; i++){

boxAll[i].addEventListener('click', () => {

// 기존 active 제거
for(let j = 0; j < boxAll.length; j++){

boxAll[j].classList.remove('active');

}

// 클릭한 박스 active 추가
boxAll[i].classList.add('active');

});

}

</script>

</body>
</html>
#문제 5 : querySelectorAll + for문 + active

첨부 파일

0개
첨부된 파일이 없습니다.

댓글 / 답글

0개
댓글을 작성하려면 로그인하세요.
아직 댓글이 없습니다.