JavaScript에서는 HTML 문서를 읽어올 뿐만 아니라 변경도 할 수 있음.
HTML문서를 하나의 객체로 사용할 수 있음 --> document
document -> *.js 파일에 연결된 HTML 문서를 가져온다
document.title -> 해당 HTML 문서에서 title 부분을 가져온다
<!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 autofocus class="hello" id="title">Grab me!</h1>
<script src="app.js"></script>
</body>
</html>
const title = document.getElementById("title");
console.log(title);
console.dir(title); // title에 대해서 자세하게 볼 수 있음
title.innerText = "Got you!"
const hellos = document.getElementsByClassName("hello"); // -> 배열
const title = document.getElemnetsByTagName("h1"); // -> 배열
// CSS 선택자를 통해 html과 js를 연결
const title = document.querySelector(".hello h1"); // -> 하나의 elemnet
const title = document.querySelectorAll(".hello h1"); // -> 배열
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
h1.style.color = blue;
}
function handleMouseEnter() {
h1.innerText = "mouse is here";
}
h1.addEventListener("click", handleTitleClick);
h1.onclick = handleTitleClick;
// click했을때 handleTitleClick를 호출해라
// handleTitleClick() <- ()를 뺸 이유는 자바 스크립트가 대신 실행해주길 원해서
h1.addEventListener("mouseenter", handleMouseEnter);
h1.onmouseenter = handleMouseEnter;
// addEventListener를 선호하는 이유
// : 나중에 .removeEventListener를 통해 event listener를 제거할 수 있기 때문
function handleWindowResize() {
document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy() {
alert("copier");
}
function handleWindowOffline() {
alert("SOS no WIFI");
}
function handleWindowOnline() {
alert("ALL GOOD");
}
window.addEventListener("resize", handleWindowResize);
// window는 document처럼 js에서 기본제공, 창크기 변경 event
window.addEventListener("copy", handleWindowCopy);
window.addEventListener("offline", handleWindowOffline);
window.addEventListener("online", handleWindowOnline);
*event 종류
: console.dir("element"); 했을 때 on이 붙어있는 것들
on 떼고 사용하면 됨
const h1 = document.querySelector("h1");
function handleTitleClick() {
const currentColor = h1.style.color;
let newColor;
if (currentColor === "blue") {
newColor = "tomato";
} else {
newColor = "blue";
}
h1.style.color = newColor;
}
h1.addEventListener("click", handleTitleClick);
=> js와 css
h1 {
color : blue;
}
.clicked {
color: tomato;
}
const h1 = document.querySelector("h1");
function handleTitleClick() {
const clickedClass = "clicked";
if (h1.className === clickedClass) {
h1.className = "";
} else {
h1.className = clickedClass;
}
}
//=> 원래 클래스 이름이 변경되지 않게 하기 위해
function handleTitleClick() {
const clickedClass = "clicked";
if (h1.classList.contains(clickedClass)) { // class명 있는지 확인
h1.classList.remove(clickedClass); // 클래스명 제거
} else {
h1.classList.add(clickedClass); // 클래스명 추가
}
}
// => 토글() 사용
function handleTitleClick() {
h1.classList.toggle("clicked");
}
h1.addEventListener("click", handleTitleClick);