728x90
300x250
SMALL
버튼 클릭 시 클래스 토글(활성화 상태 표시)
다음 jQuery를 Vanilla JS로 변경해 보자
<style>
.active{
background: green;
color: white;
}
</style>
<button class="btn3">토글 버튼</button>
<script>
$('.btn3').click(function(){
$(this).toggleClass('active');
});
</script>
Vanilla JS
<style>
.active{
background: green;
color: white;
}
</style>
<button class="btn3">토글 버튼</button>
<script>
document.querySelector(".btn3").addEventListener("click",function(){
this.classList.toggle("active");
})
</script>
1. document.querySelector(".btn3")
html에서 .btn3클래스가 붙은 첫 번째 요소를 선택
2. .addEventListener("click", function*(){...})
해당 버튼을 클릭했을때 실행할 함수 (이벤트 핸들러)를 지정
3. this.classList.toggle("active")
- this.는 현재 클릭한 요소 자신을 의미함
- classList는 해당 요소에 적용된 클래스 목록을 관리할 수 있는 DOM 객체
- toggle("active")는
- active 클래스가 없으면 추가 있으면 제거
728x90
반응형
LIST
'javaScript > Vanilla JS' 카테고리의 다른 글
Vanilla JS 간단한 모달창 열기/닫기 (0) | 2025.04.22 |
---|---|
Vanilla JS 동적 요소 추가/삭제 (0) | 2025.04.21 |
Vanilla JS 반복문, 동적 요소 제어 (0) | 2025.04.20 |
Vanilla JS 입력창에 입력한 값 가져오기 (0) | 2025.04.19 |
Vanilla JS 기초 연습 - 버튼 클릭하면 alert 띄우기 (0) | 2025.04.17 |
댓글