● Document
Document는 이미 브라우저에 존재하는 object이다.
JavaScript는 HTML에 접근하고 읽을 수 있게 설정되어있는데, HTML의 element를 (title 등) document로 불러올 수 있다.
● getElementById()
document 함수의 일종으로, HTML에서 id를 통해 element를 찾아준다.
getElementsByClassName(), getElementsByTagName() 등도 동일한 역할을 수행한다.
● querySelector(), querySelectorAll() 가장 많이 사용
element를 CSS 방식으로 검색하는 함수이며 하나의 element를 return한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Monmentum</title>
</head>
<body>
<div class="hello">
<h1>Grab me!</h1>
</div>
<script src="app.js"></script>
</body>
</html>
->index.html
const title=document.querySelector(".hello h1");
console.log(title);
->app.js
getElementById(), getElementsByClassName 등의 함수들은 인자로 Id, ClassName 등을 준다는 것을 알고 있지만, querySelector에서는 hello가 class name이라는 것과 (.hello) 그 안의 h1을 명시해줘야함.
class가 아니라 id면 #으로 가져오기.
h1이 여러 개인 경우,
querySelector()은 가장 처음 element만 가져온다.
querySelectorAll() 조건에 맞는 h1이 여러개 들어있는 array를 가져다준다.
● addEventListener()
사용자의 이벤트를 듣는다.
Click me!를 클릭할 때마다 색깔이 blue로 바뀌는 예제.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Monmentum</title>
</head>
<body>
<div class="hello">
<h1>Click me!</h1>
</div>
<script src="app.js"></script>
</body>
</html>
->index.html
const title=document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
title.style.color="blue";
}
//이벤트가 발생하면 전달할 함수 전달
title.addEventListener("click",handleTitleClick);
->app.js
● window.addEventListener()
두개의 인자가 쉼표로 연결됨. 첫번째 인자는 listen할 window element의 이벤트(resize, copy, offline, online ), 두번째 인자는 전달할 함수
● JavaScript에서 listen하고 싶은 event를 찾는법
1. 구글링: 찾고 싶은 element의 이름(ex. h1)+ html element+mdn(Mozilla Developer Network)을 검색한 후,
Web APIs라는 문장이 포함되는 페이지 찾기
2. console.dir()을 통해서 찾고 싶은 element를 console에 출력시켜 직접 찾기.
property 이름 앞에 on이 붙어있다면, 그게 바로 event listener.
이제부터는 CSS에 정의된 class name들로 HTML element에서 숨기고 표시하는 방법을 설명하겠다.
● classList
class들의 목록으로 작업할 수 있게한다.
다음은 classList가 아닌 className을 사용한 코드이다. className은 이전 class를 고려하지 않고 모든걸 교체하기 때문에 문제가 생길 수 있다.
const h1=document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
if(h1.className==="active"){
h1.className="";
}
else{
h1.className="active";
}
}
h1.addEventListener("click",handleTitleClick);
다음은 classList로 수정된 코드이다.
const h1=document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
const clickedClass="active";
//classList가 clickedClass를 가지고 있는지 확인해 있으면 제거 없으면 추가
if(h1.classList.contains(clickedClass)){
h1.classList.remove(clickedClass);
}
else{
h1.classList.add(clickedClass);
}
}
h1.addEventListener("click",handleTitleClick);
● toggle(token)
toggle함수는 token이 존재한다면 토큰을 제거하고 존재하지 않는다면 토큰을 추가한다.
아래 코드는 위의 classList로 구현된 코드와 같은 역할을 한다.
(개념 이해를 위한 예시로는 한번 누르면 스크린을 잠그고 다시 한번 누르면 스크린을 켜주는 스마트폰의 전원버튼 같은 것이 있다.)
const h1=document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
h1.classList.toggle("active");
}
h1.addEventListener("click",handleTitleClick);
toggle()을 사용하면 위의 if~else문을 한줄로 해결할 수 있다.