classList
classList은 HTML 요소의 class 속성에 저장된 값을 제어하는 키워드이다.
주요 함수)
- add(string) : 새로운 'string' 값을 class 속성에 추가
- remove(string) : 'string' 값을 class 속성에서 제거
- toggle(string) : add와 remove가 합쳐진 상태
- contains(string) : 'string'이 class 속성에 있는지 여부 확인 => 들어가 있으면 true, 없으면 false
- replace(str1, str2) : class 속성에 str1이 있으면 str2로 변경
아래 코드는 classList의 주요 함수를 활용한 예제이다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ClassList</title>
<style>
div {
width: 200px;
height: 100px;
}
.st1 { border: 1px solid; }
.st2 {
border: 3px dashed;
background-color: yellow;
}
</style>
</head>
<body>
<div>BOX</div>
<button>toggle</button>
<button>change</button>
</body>
<script>
const box = document.querySelector("div");
const btn = document.querySelectorAll("button");
box.classList.add("st1");
btn[0].addEventListener("click", function(){
box.classList.toggle("st1");
if(box.classList.contains("st2")){
box.classList.remove("st2");
}
});
btn[1].addEventListener("click", function(){
box.classList.replace("st1", "st2");
})
</script>
</html>
retrun
return 키워드는 '함수의 종료'를 의미하기도 하고, 함수 내부에서 처리된 결과값 반환에 쓰이기도 한다.
this
this 키워드는 이벤트가 발생한 '요소 자신'을 의미한다.
이벤트 처리 속서에서 this를 매개변수로 사용하면 함수에서 요소를 가져와서 처리할 수 있다.
'Js' 카테고리의 다른 글
16. 객체 (0) | 2022.09.09 |
---|---|
14. 함수 (0) | 2022.09.05 |
13. 다양한 for문 (0) | 2022.09.02 |
12. 배열 메소드 (0) | 2022.09.02 |
11. 참고 (0) | 2022.09.01 |