ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JavaScript] 자바스크립트 기초
    WEB/JavaScript 2020. 7. 8. 22:28

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <title>Hello World!</title>
            <link rel="stylesheet" href="index.css">
        </head>
        <body>
            <h1 id="title" class="btn">Hello World!</h1>
            <script src="index.js"></script>
        </body>
    </html>

     

    index.css

    body {
        background-color: peru;
    }
    
    h1 {
        color: #34495e;
        transition: color 0.5s ease-in-out;
    }
    
    .clicked {
        color: #7f8c8d;
    }

     

    index.js

    // const title = document.getElementById("title");
    // const title = document.getElementsByClassName("btn");
    const title = document.querySelector("#title");
    
    const CLICKED_CLASS = "clicked";
    
    function handleClick() {
    //     const hasClass = title.classList.contains(CLICKED_CLASS)
    //     if(!hasClass) {
    //         title.classList.add(CLICKED_CLASS);
    //     } else {
    //         title.classList.remove(CLICKED_CLASS);
    //     }
    
    title.classList.toggle(CLICKED_CLASS);
    } 
    
    
    
    function init() {
        title.addEventListener("click", handleClick);
    }
    
    init();
    

     

    // 해당 아이디 이름을 가진 태그 요소를 찾음

    const title = document.getElementById("title"); 

     

     // 해당 클래스 이름을 가진 태그 요소를 찾음 
    const title = document.getElementsByClassName("btn");

     

    // 해당 아이디("#") 이름(".") 혹은 클래스 이름을 가진 태그 요소를 찾음
    const title = document.querySelector("#title"); 

     

    /* classList : 클래스를 쉽게 조작할 수 있게 도와줌 */

    // 해당 클래스를 필요에 따라 삽입

    classList.add(CLICKED_CLASS)

     

    // 해당 클래스를 필요에 따라 제거

    classList.remove(CLICKED_CLASS) 

     

    // 해당 클래스가 포함되어 있는지 확인(Boolean)

    classList.contains(CLICKED_CLASS) 

     

    // 해당 클래스가 있는지 확인하고 있으면 제거, 없으면 삽입

    classList.toggle(CLICKED_CLASS) 

     

    댓글

Designed by Tistory.