가취공부하자

[Javascript] classList 함수 (Toggle, add, remove) 본문

Web

[Javascript] classList 함수 (Toggle, add, remove)

keepGGoing 2022. 10. 6. 22:44

classList함수중 

Toggle은  해당 태그에 A라는 class있으면 삭제, 없으면 추가하는 함수이다.

tag.classList.toggle(A);

const title = document.querySelector("div.hello:first-child h1");

function hanldleTitleClick(){
    const varClciked = 'Clicked';
    if(title.classList.contains(varClciked) )
    {
        title.classList.remove(varClciked);
    }else
    {
        title.classList.add(varClciked);
    }
}

위의 코드를 toggle을 사용하면 아래처럼 줄일 수 있다

//hello라는 class를 가진 div의 h1 태그이며 first-child 인 element 가져오기
const title = document.querySelector("div.hello:first-child h1");

function hanldleTitleClick(){
    title.classList.toggle("Clicked");
}

.

'Web' 카테고리의 다른 글

사용자 커뮤니케이션  (0) 2021.07.14