📌 className 속성
<script>
var 변수명 = 객체선택.className;
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS - Class 속성</title>
</head>
<body>
<h1 class="title" id="text">제목태그</h1>
<script>
var text = document.getElementById('text')
var cName = text.className;
alert(cName);
</script>
</body>
</html>
<script>
객체선택.className = '클래스명';
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS - Class 속성</title>
</head>
<body>
<h1 id="text">제목태그</h1>
<script>
var text = document.getElementById('text')
text.className = 'title';
</script>
</body>
</html>
📌 classList 속성
<script>
객체선택.classList.length;
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS - Class 속성</title>
</head>
<body>
<h1 class="test01">h1태그</h1>
<h1 class="test01 test02">h1태그</h1>
<h1 class="test01 test02 test03">h1태그</h1>
<script>
var h1 = document.getElementsByTagName('h1');
console.log(h1[0].classList.length);
console.log(h1[1].classList.length);
console.log(h1[2].classList.length);
</script>
</body>
</html>
<script>
객체선택.classList.add('클래스명1','클래스명2',...);
객체선택.classList.remove('클래스명1','클래스명2',...);
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS - Class 속성</title>
<style>
.active{
background-color: black; color: pink;
}
</style>
</head>
<body>
<h1 id="text">제목태그</h1>
<hr>
<button id="add">클래스추가</button>
<button id="remove">클래스제거</button>
<script>
var text = document.getElementById('text');
var add = document.getElementById('add');
var remove = document.getElementById('remove');
add.addEventListener('click',function(){
text.classList.add('active');
});
remove.addEventListener('click',function(){
text.classList.remove('active');
});
</script>
</body>
</html>
<script>
객체선택.classList.toggle('클래스명');
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS - Class 속성</title>
<style>
.active{
background-color: black; color: pink;
}
</style>
</head>
<body>
<h1 id="text">h1태그</h1>
<script>
var text = document.getElementById('text');
text.addEventListener('click',function(){
this.classList.toggle('active');
});
</script>
</body>
</html>
-문서객체가 해당 클래스를 갖고 있는 유무에 따라 true/false를 반환
<script>
객체선택.classList.contains('클래스명');
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS - Class 속성</title>
<style>
.active{
background-color: lightgoldenrodyellow; color: orangered;
}
</style>
</head>
<body>
<h1 id="text">제목태그</h1>
<p id="test"></p>
<script>
var text = document.getElementById('text');
var test = document.getElementById('test');
text.addEventListener('click',function(){
this.classList.toggle('active');
var is = this.classList.contains('active');
if(is){
test.textContent = '클래스추가';
}else{
test.textContent = '클래스제거';
}
});
</script>
</body>
</html>