knj
Knj
knj
전체 방문자
오늘
어제
  • 분류 전체보기 (55) N
    • 정보처리기사 (2)
    • Spring (12)
    • JS (2)
    • java (6)
    • 컴퓨터 시스템 (9)
      • Chapter 1 컴퓨터 시스템 기초 (8)
      • Chapter 2 정보의 표현과 처리 (1)
    • 알고리즘 (4)
    • CODE (5)
    • 컴퓨터 네트워킹 (5)
      • Chapter 1 - 컴퓨터 네트워크와 인터넷 (5)
    • 혼자공부 하는 컴퓨터구조 운영체제 (5)
      • Chapter1 (2)
      • Chapter2 (1)
      • Chapter3 (1)
    • 컴퓨터 네트워크 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
knj

Knj

JS

JS - toggle

2022. 4. 26. 19:20

DOMTokenList.toggle()

  1. remove / add 를 동시에 갖고 있다.
  2. 토큰이 존재하면 토큰 제거, 존재 하지 않는다면 토큰 추가.
  3. 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
    'JS' 카테고리의 다른 글
    • Javascript - console.dir( )
    knj
    knj

    티스토리툴바