2019백업

Javascript-classList

728x90

 

classList

자바스크립트에서 class 추가 삭제 등 클래스를 조작하기 위해 추가된 프로퍼티이다.

Method

add(class1, class2, ...) Adds one or more class names to an element.

If the specified class already exist, the class will not be added
contains(class) Returns a Boolean value, indicating whether an element has the specified class name.

Possible values:

  • true - the element contains the specified class name
  • false - the element does not contain the specified class name
item(index) Returns the class name with a specified index number from an element. Index starts at 0.

Returns null if the index is out of range
remove(class1, class2, ...) Removes one or more class names from an element.

Note: Removing a class that does not exist, does NOT throw an error
toggle(class, true|false) Toggles between a class name for an element.

The first parameter removes the specified class from an element, and returns false. 
If the class does not exist, it is added to the element, and the return value is true.

The optional second parameter is a Boolean value that forces the class to be added or removed, regardless of whether or not it already existed. For example:

Remove a class: element.classList.toggle("classToRemove", false); 
Add a class: element.classList.toggle("classToAdd", true);

Note: The second parameter is not supported in Internet Explorer or Opera 12 and earlier.

 

toggle 사용 예시

 

HTML코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang=ko dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>event</title>
    <link rel="stylesheet" href="./toggle.css">
  </head>
  <body>
    <div>
      <p id="title" class="btn">hello javascript</p>
    </div>
    <script src="toggle.js" charset="utf-8"></script>
  </body>
</html>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

JS코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const title = document.querySelector("#title");
const CLICKED_CLASS = "clicked";
 
function handleClick() {
    
    // toggle method 동작 방식
  // const hasClass = title.classList.contains(CLICKED_CLASS);
  // if (hasClass) {
  // } else {
  // }
}
 
function init() {
  title.addEventListener("click", handleClick);
}
init();
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

결과화면

console창에서 hello javascript를 클릭할때마다 클래스의 값이 변경되는 것을 확인하였다.

 

 

jQuery에서 class제어 

http://blim.co.kr/archives/160

반응형

'2019백업' 카테고리의 다른 글

ConnectionURL 찾은 내용  (0) 2020.01.05
코드블럭 테스트  (0) 2019.12.25
JavaScript - Variable  (0) 2019.07.26
JavaScript - 노드복제와 템플릿 태그  (0) 2019.07.24
JavaScript - 노드조작: 메뉴추가  (0) 2019.07.24