classList toggle

2019. 12. 21. 21:17JavaScript

728x90

진부한 토글

// Tedious toggle
if (shadesEl.classList.contains('rad')) {
  shadesEl.classList.remove('rad');
} else {
  shadesEl.classList.add('rad');
}

classList property를 사용한 토글

coolButton.addEventListener('click', () => {
  shadesEl.classList.toggle('cool');
});

classList toggle의 두번째 매개변수는 boolean값 자리이다.

let someCondition;

let b = shadesEl.classList.toggle('cool', !!someCondition);
console.log(b);
// someConditon이 undefined이기 때문에 두번째 매개변수의 값은 False이다
// False이니까 cool이라는 클래스는 제거된다
// 콘솔 출력값도 False

someCondition = 'I wear my sunglasses at night';

let c = shadesEl.classList.toggle('cool', !!someCondition);
console.log(c);
// 이때는 someConditon의 값이 True이니까 cool이라는 class가 추가되고
// 콘솔 출력값도 True

 

참고자료:

https://alligator.io/js/classlist/

 

 

728x90
반응형