- document : 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>Momentum</title>
</head>
<body>
<h1 id ="title">Grab me!</h1>
<div class = "hello">
<h1>hihi 1</h1>
</div>
<div class = "hello">
<h1>hihi 2</h1>
</div>
<div class = "hello">
<h1>hihi 3</h1>
</div>
<script src="app.js"></script>
</body>
</html>
console.dir(document.getElementById("title")); // h1태그에서 가져올 수 있는 모든 속성 출력
document.getElementsByClassName("name")
document.querySelector(".hello h1") // 첫번째 것 return
document.querySelectorAll(".hello h1") // 배열로 return
const title = document.querySelector("div.hello:first-child h1");
title.style.color = blue; // 색상 바꾸기
function handleTitleClick(){
console.log("title was clicked!");
}
title.addEventListener("click", handleTitleClick); // 클릭 이벤트
listen 하고 싶은 event를 찾는 가장 좋은 방법
- 예를 들어,
h1 html element mdn
검색 후Web APIs
가 있는 항목을 클릭
- 또는 console.dir(document.querySelector("h1")) 으로 출력된 것을 확인
💡 property 이름 앞에 on이 붙어있다면, event listener
javascript로 css 변경하기
<!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>Momentum</title>
</head>
<body>
<h1 id ="title">Grab me!</h1>
<div class = "hello">
<h1>hihi 1</h1>
</div>
<div class = "hello">
<h1>hihi 2</h1>
</div>
<div class = "hello">
<h1>hihi 3</h1>
</div>
<script src="app.js"></script>
</body>
</html>
h1{
color: cornflowerblue;
}
.active{
color:tomato;
}
const h1Tag = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
h1Tag.className = "active";
}
h1Tag.addEventListener("click", handleTitleClick);
👉 하지만, css에서 class가 추가되면 javascript도 변경해줘야하는 번거로움이 있음
따라서, 다음과 같이 사용할 수 있다.
function handleTitleClick(){
if(h1Tag. classList.contains("active")){
};
}
class 삭제/추가하기
const h1Tag = document.querySelector("div.hello:first-child h1");
const clickedClass = "clicked";
h1Tag.classList.remove(clickedClass);
h1Tag.classList.add(clickedClass);
h1Tag.classList.toggle(clickedClass); // 클래스 이름이 있으면 삭제, 없으면 추가
addEventListener 동작 방식
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");
function onLoginSubmit(event){
event.preventDefault(); // 새로고침을 막음
console.log(loginInput.value);
}
loginForm.addEventListener("submit",onLoginSubmit);
- 브라우저는 우선 onLoginSubmit function을 호출하고 브라우저는 브라우저 내에서 event로부터 정보를 잡아내서 onLoginSumbmit 버튼을 누른다.
반응형
댓글