[JS 이론] DOM Manipulation - classList

Minha Sohn·2022년 12월 12일
0

[JS] 이론 공부

목록 보기
2/11

classlist로 자바스크립에서 특정 클래스를 제어하는 방법에 대해 알아보자.

** Element.clasList 는 element의 class 속성의 컬렉션인 활성 DOMTokenList를 반환하는 읽기 전용 프로퍼티이다.

문법
const elementClasses = elementNodeReference.classList;

add

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

  • 지정한 클래스 값을 추가한다. (여러개 동시 삽입 가능)
  • 만약 추가하려는 클래스의 element의 class 속성이 이미 존재한다면 무시한다.
var target = document.getElementById("btn");

function changeButtonOnclick() {
  target.classList.add('changeColor'); // HTML에 클래스 없다 가정 후 추가
  target.innerText = '버튼 클릭 성공!'
}

target.addEventListener('click',changeButtonOnclick) // 버튼 클릭시 function changeButtonOnclick 작동

remove

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

  • 지정한 클래스 값을 제거한다. (여러개 동시 제거 가능)
  • 만약 추가하려는 클래스의 element의 class 속성이 이미 존재한다면 무시한다.
// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");

// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

item

item( Number )

classList collection의 인덱스를 이용하여 클래스 값을 반환한다.

toggle

toggle( String [, force] )

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

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

contains

contains( String )

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

replace

replace( oldClass, newClass )

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

// replace class "foo" with class "bar"
div.classList.replace("foo", "bar");
profile
개발자를 꿈꾸는 코린이!

0개의 댓글