첫번재로 HTML과 상호작용 하기 위해서는 HTML 요소에 접근해야 합니다.

요소에 접근하는 방법은 document를 사용하면 됩니다.

1. document란?

현재 javascript를 사용하고 있는 HTML 파일을 document라고 부릅니다. 즉, <script src=”현재 js파일”></script>를 적은 파일을 가리킵니다.

2. getElementById & getElementByClassName

첫번째로 getElementById와 getElementByClassName에 대해서 설명하겠습니다.

이름에서 보시다시피 id와 class의 이름으로 요소를 가져오는 방법입니다. 위의 index.html에서 id가 title인 요소와 class가 smallTitle인 요소를 가져와 보겠습니다.

//index.html

<h1 id="title">나는 제목</h1>
<h3 class="smallTitle">나는 소제목</h3>

.
.
.
<script src="index.js></script>
//index.js

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

이제 title과 small title에는 각각, “<h1 id="title">나는 제목</h1>”와 “<h3 class="smallTitle">나는 소제목</h3>”가 담겼습니다.

3. querySelector

그렇다면 h1 요소 전체나 h3 요소 전체를 가져오고 싶을 때는 어떻게 해야 할까요?

querySelector를 사용하면 됩니다. querySelector는 html의 방식으로 document에 접근할 수 있게 해줍니다.

예시를 보겠습니다.

//index.js

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

const title2 = document.querySelector("#title");
const smallTitle2 = document.querySelector(".smallTitle");

위 두 줄의 코드와 아래 두줄의 코드는 동일한 기능을 수행합니다.

단, querySelector를 사용할 때는 #이나 .과 같은 식별자를 추가해 주어야 한다는 것을 염두해야 합니다.

//index.js
const title2 = document.querySelector("h1");
const smallTitle2 = document.querySelector("h3");