[Javascript] className(), classList()와 메소드

newsilver·2021년 7월 26일
2

Javascript

목록 보기
11/16
post-thumbnail

className

✏️ className은 특정 엘리먼트의 클래스 속성의 값을 가져오거나 설정할 수 있다.

var cName = element.className; or
element.className = cName;


classList

✏️ classList는 읽기 전용 프로퍼티이다.

공백으로 구분된 문자열인 element.className을 통해 엘리먼트의 클래스 목록에 접근하는 방식을 대체하는 간편한 방법이다.

메소드

1. add

classList.add( String [, String [, ...]] )

지정한 클래스 값을 추가한다.
만약 추가하려는 클래스가 엘리먼트의 class 속성에 이미 존재한다면 무시한다.

2. remove

classList.remove( String [, String [, ...]] )

지정한 클래스 값을 제거한다.
🚨 존재하지 않는 클래스를 제거하는 것은 에러를 발생하지 않는다.

3. item( Number )

콜렉션의 인덱스를 이용하여 클래스 값을 반환한다.

4. toggle

classList.toggle( String [, force] )

하나의 인수만 있을 때 클래스 값을 토글링한다.
즉, 클래스가 존재한다면 제거하고 false를 반환하며, 존재하지 않으면 클래스를 추가하고 true를 반환한다.

두번째 인수가 있을 때 두번째 인수가 true로 평가되면 지정한 클래스 값을 추가하고 false로 평가되면 제거한다.

5. contains

classList.contains( String )

지정한 클래스 값이 엘리먼트의 class 속성에 존재하는지 확인한다.

6. replace

classList.replace( oldClass, newClass )

존재하는 클래스를 새로운 클래스로 교체한다.


✏️ addEventListener로 className 바꾸기

const textElement = document.getElementById("text");
const CLICKED_CLASS = "clicked";

function handleClick() {
    const currentClass = animalElement.className;
    if (currentClass !== CLICKED_CLASS) {
        textElement.className = CLICKED_CLASS;
    } else {
        textElement.className = "";
    }
}

function init() {
    textElement.addEventListener("click", handleClick);
}

init();


id가 "text"인 엘리먼트에 "clicked" class 한 개만 사용할 수 있다.
contains,toggle 메소드로 해결한다.

✏️ contains 메소드 사용

const textElement = document.getElementById("text");
const CLICKED_CLASS = "clicked";

function handleClick() {
    const hasClass = textElement.classList.contains(CLICKED_CLASS);
    if (hasClass) {
        textElement.classList.remove(CLICKED_CLASS);
    } else {
        textElement.classList.add(CLICKED_CLASS);
    }
}

function init() {
    textElement.addEventListener("click", handleClick);
}

init();

✏️ toggle 메소드 사용
toggle로 더 간단하게 코드를 작성할 수 있다.

const textElement = document.getElementById("text");
const CLICKED_CLASS = "clicked";

function handleClick() {
    textElement.classList.toggle(CLICKED_CLASS);
}

function init() {
    textElement.addEventListener("click", handleClick);
}

init();

실행 화면은 모두 똑같다.

profile
이게 왜 🐷

0개의 댓글