Javascript

JS classList

xxoyeong 2020. 8. 4. 22:43

classList는 메소드를 가진다 즉, 함수를 사용할 수 있다.

add, remove, contain, toggle...

 

ex) 

const title = document.querySelector("#title");

 

title.className = '클래스이름추가';  =  title.classList.add('클래스이름추가');

title.className = '';  = title.classList.remove('클래스이름추가');

title.classList.contains = '클래스이름추가';    -> class name에 '클래스이름추가' 라는 class있는지 확인 

   -> <h1 id = "title"> Work! </h1>

           일 때 add해주면 <h1 id = "title 클래스이름추가"> Work! </h1>

           remove해주면 다시 <h1 id = "title"> Work! </h1>

 

title.classList.toggle =

function handleClick(){

    title.classList.toggle('클래스이름추가');

}

                    =

 

function handleClick(){

    const hasClass = title.classList.contains('클래스이름추가');

    if(hasClass) {

           title.classList.remove('클래스이름추가');

         } else {

            title.classList.add('클래스이름추가');

         }

}