DOMTokenList.toggle()
- remove / add 를 동시에 갖고 있다.
- 토큰이 존재하면 토큰 제거, 존재 하지 않는다면 토큰 추가.
- if-else 를 쓰는것 보다 코드 길이를 줄여줄 수 있다.
반환값
호출 후 목록에 있는지 여부를 나타내는 boolean 값 true또는 false
const span = document.querySelector("span");
const classes = span.classList;
span.addEventListener('click', function() {
const result = classes.toggle("c");
if (result) {
span.textContent = `'c' added; classList is now "${classes}".`;
} else {
span.textContent = `'c' removed; classList is now "${classes}".`;
}
})
DOMTokenList.toggle() - Web APIs | MDN
The toggle() method of the DOMTokenList interface removes an existing token from the list and returns false. If the token doesn't exist it's added and the function returns true.
developer.mozilla.org
'JS' 카테고리의 다른 글
Javascript - console.dir( ) (0) | 2022.05.06 |
---|