서버와 통신을 하거나 다른 복잡한 일들을 처리할 때 js 파일에서 처리하게 되는데 그때 HTML의 element들을 자유자재로 다룰 수 있게 되야 여러 복잡한 처리를 원할하게 할 수 있게 됨
// HTML
<body>
<h1 id="title" class="hello">Grab me!</h1>
<script src="app.js"></script>
</body>
const title = document.getElementById("title");
console.dir(title);
주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 요소를 반환함
console.log, console.dir
console.log
는 요소를 HTML과 같은 트리 구조로 출력함console.dir
은 요소를 JSON과 같은 트리 구조로 출력함const title = document.getElementById("title");
title.innerText = "Got you" ;
// html
<div class="hello">
<h1>Grab me!</h1>
</div>
const hellos = document.getElementsByClassName("hello");
getElementsByClassName
많은 요소를 한번에 가지고 와야하는 경우에 사용
const title = document.querySelector(".hello h1");
querySelector
요소를 CSS 방식으로 검색할 수 있음, 단 하나의 요소를 리턴함
→ 'hello'란 class내부에 있는 h1을 가지고 올 수 있음
querySelectorAll
셀렉터 안의 조건에 부합하는 모든 요소를 배열로 출력함
console.dir 실행시 이름 앞에 on이 붙어있으면 event listener
const title = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
title.style.color = "blue";
}
title.addEventListener('click', handleTitleClick);
addEventListener()
지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정함
title.onclick = handleTitleClick;
removeEventListener 통해 event listener를 제거할 수 있음