JavaScript
[JavaScript] class 제어(수업)
FRDYtheme
2022. 12. 9. 10:16
JS에서의 클래스 제어
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>클래스 제어</title>
<style>
.bg {
background-color: lightskyblue;
}
.orange {
background-color: orange;
}
.bold {
font-weight: bold;
font-size: 1.4em;
}
.normal {
font-weight: normal;
font-size: 24px;
}
.btn {
width: 100px;
text-align: center;
border: 3px solid #000;
padding: 5px 10px;
}
.btn.style {
background-color: tomato;
color: #fff;
}
</style>
</head>
<body>
<h1>js에서의 클래스 제어</h1>
<div class="btn">버튼</div>
<p></p>
<ul>
<li>텍스트1</li>
<li>텍스트2</li>
<li>텍스트3</li>
</ul>
<script>
// .classList.add(); 클래스 속성 추가
// .classList.remove(); 클래스 속성 삭제
// .classList.toggle(); .add(), .remove()의 반복
</script>
</body>
</html>
.classList.add() : 클래스 속성 추가
document.body.classList.add('bg')
const btn = document.querySelector('.btn')
btn.classList.add('style')
.classList.remove() : 클래스 속성 삭제
btn.classList.remove('style');
.classList.toggle() : add, remove의 반복
btn.addEventListener('click', () => btn.classList.toggle('style'))
// btn을 클릭하면 style 추가 한번 더 클릭하면 style 제거
.classList.contains() : 해당 클래스의 속성 여부를 true와 false로 반환
const p = document.querySelector("p");
const isBold = p.classList.contains("bold");
console.log(isBold); // false
.className : 클래스 값을 가져오거나 변경하며, 없으면 추가한다.
console.log(h1.className) // 공백
h1.className = 'normal'
console.log(h1.className) // normal
h1.className = 'orange'
// 새로 orange 클래스가 추가되는 게 아니라 normal 클래스를 orange로 변경함.
classList.replace('탐색 클래스', '변경 할 클래스')
// .replace('탐색 클래스', "변경할 클래스")
btn.addEventListener('click', () => {
li.forEach(li => li.classList.replace('orange', 'bold'))
}) // btn을 클릭하면 li 전부의 클래스 orange가 bold로 변경