
HTML과의 상호작용을 위해서이다. JavaScript를 통해 HTML을 읽어올 수 있고 변경 또한 가능하다.
document.title = "Hi" // 화면의 title 부분이 Hi로 변경된다.
documentobjectJavaScript에서 HTML에 접근할 수 있는 키워드getElementByIdid에 할당된 element를 가져온다.
// id="title"인 element를 찾는다.
const title = document.getElementById("title");
getElementsByClassNameclass에 할당된 element를 가져온다. array 형태로 많은 element를 가져온다.// class="hello"인 element를 찾는다.
const title = document.getElementsByClassName("hello");
HTMLCollection [div.hello] 0: div.hello length: 1
getElementsByTagNamearray 형태로 많은 element를 반환한다.// h1 태그에 해당하는 element를 찾는다.
const title = document.getElementsByTagName("h1");
HTMLCollection [h1] 0: h1 length: 1
querySelector (★★★★★)CSS selector 형태로 element를 찾는다. 앞으로 많이 쓰일 예정.// class="hello"인 element 중 h1 태그에 해당하는 element를 찾음
const title = document.querySelector(".hello h1");
<h1>Grab me!</h1>
querySelector의 경우 하나의 element만 반환하는데, 여러 개를 찾아오고 싶으면 array형태로 반환하는 querySelectorAll을 사용하면 된다.querySelector("#hello") == getElementById("hello")