[JavaScript] document

문규찬·2021년 7월 14일
0
post-thumbnail

노마드코더 영상을 토대로 작성하였습니다.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>it's Moon!</title>
  </head>
  <body>
    <div class="title">what is your Name?</div>
    <script src="app.js"></script>
  </body>
</html>

head 안에 link로 style.css 파일과
body 안에 script로 app.js 를 불러오고 있습니다.

app.js 를 살펴보면

App.js

const title = document.querySelector("div.title");
title.style.color = "black";

function handleClick() {
  const titleColor = title.style.color;
  let newColor;
  if (titleColor === "black") {
    newColor = "white";
  } else {
    newColor = "black";
  }
  title.style.color = newColor;
}

title.addEventListener("click", handleClick);

정적이던 웹 페이지를 script app.js 를 통해 각 요소에 어떻게 접근하고 동적으로 바꿀 수 있는지 살펴 보겠습니다.

우선 console.log (document) / console.dir(document) 를 살펴보면

처음에 작성했던 index.html의 내용과 document 객체 안의 수많은 프로퍼티 값을 확인 할 수 있습니다. 그 중에서도 body 안에 div class="title" 부분에 접근하고 싶다면 document . getElementsByClassName, document . getElementsById, 로도 접근이 가능하지만 querySelector 를 사용했습니다. (같은 태그에 모두 적용하고 싶다면 querySelectorAll)

이어서 const title = document.querySelector("div.title");
로 title을 지정해주고

title.addEventListener("click", handleClick); 를 통해
원하는 함수 기능을 넣어주었습니다.

0개의 댓글