Summary #3.0 ~ #3.8
1. Document 개념
document는 브라우저에 이미 존재하는 object (documnet는 자바스크립트 관점에서의 HTML)
모든 것은 documnet로 부터 시작함(document는 web site를 의미함)
2. HTML in JavaScript
<!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>
<script src="app.js"></script>
</body>
</html>
documet.getElementByID("") : HTML에서 ID를 통해 element를 찾아 줌 --> console창에서 확인 가능
element를 찾고 나면, 해당 HTML에서 변경 가능
자바스크립트는 HTML elemet를 가지고 오는 것 뿐, 자체를 보여주지는 않음
const title = document.getElementById("title");
title.innerText = "Got you!"
//innerText : element안의 text 값을 가져옴

3. QuerySelector (getElementById 보다 많이 사용)
getElementByClassName("") : HTML에서 class name을 통해 element를 검색
getElementsByClassName("") : 많은 element를 한 번에 가지고 와야 하는 경우. array를 return
getElementsByTagName("") : 태그 이름을 통해 element검색. array를 return
querySelector("") : element를 CSS selector 방식으로 검색할 수 있음. 단 하나의 element(동일한 값이 여러개 있다면 첫 번째 것)를 return해줌
querySelectorAll("") : selector 안의 조건에 부합하는 모든 element들을 array로 return해줌
ID를 사용하여 찾아올 수도 있다.
querySelector("#idName") 을 사용하면 된다.
4. Events
정리하면, HTML 파일에 JS file을 붙였기 때문에 우리가 JS를 통해 HTML을 가져올 수 있다는 것이다.
- property 이름 앞에 on이 붙어있다면, event listener임
- 변수명.addEventListener("이벤트명", 호출할 function);
div hello class 안에 있는 h1 불러 오는법 :
const title = documet.querySelector("div.hello:first-child h1");
element의 내부가 보고싶다면 console.log대신 console.dir을 사용하면 된다.
항목을 열어보면 element의 style을 볼 수 있다. style에 접근하려면
1. h1을 찾는다.
2. style을 찾는다
3. color를 찾는다
--> h1.style.color 로 들어가기
JavaScript에 색상을 바꾸려면 : title.style.color = "white"
Click event
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
console.log("Title was clicked!");
}
//함수 정의
title.innerText = "Hello world";
h1.style.color = "white";
h1.addEventListener("click" ,handleTitleClick);
// 1번 클릭이라는 이벤트 실행
1. handleTitleClick이라는 함수를 추가 (실행되면 console에 "title was clicked!" 문구 출력)
2. title에 addEventListener를 호출한다. (감지 할 이벤트는 click)
3. 이벤트가 감지되면 handleTitleClick 함수를 실행
5. Event +
listen할 Web event 찾는곳 -->
https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement
(싫으면 console.dir하기)
function handleTitleClick() {
console.log("Title was clicked!");
}
function hanldeMouseEneter() {
h1.style.class = "yellow";
}
function handleMouseLeave() {
h1.innerText = "white";
}
h1.addEventListener("click" ,handleTitleClick);
h1.addEventListener("mouseenter", hanldeMouseEneter);
h1.addEventListener("mouseleave", handleMouseLeave);
3가지 event 추가
1. title 클릭하면 --> Title was Clicked
2. 마우스를 올리면(mouseenter) --> 노란색
3. 마우스를 때면(mouseleave) --> 흰색
but javascript말고 css에서 하는게 옳다.
6. Event ++
if 와 else if를 사용해 색 변경
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
const currentColor = h1.style.color; //1. 선언
let newColor; //2. 선언
if(currentColor === "blue") {
newColor = "tomato";
} else {
newColor = "blue";
}
h1.style.color = newColor;
}
h1.addEventListener("click" ,handleTitleClick);
1. element를 찾아라 ( document.qeurySelector() )
2. event를 listen해라.
3. event에 반응해라.
7. CSS in javascript
style을 CSS로 바꾸는 방법
앞으로 모든 style은 CSS에서 다룰것
body {
background-color : lightpink;
}
h1 {
color : white;
}
.active {
color : yellow;
}
1. CSS file 에서 h1을 가져와서 기본색상을 바꿔줄것
2. active라는 class에 어떤 element에 지정해줘도 yellow 색상을 가지게 됨
3. JS내부의 h1을 active라는 class 에 전달하기
const h1 = document.querySelector("div.hello:first-child h1");
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
const clickedClass = "clicked";
if(h1.className === clickedClass) {
h1.className = "";
} else {
h1.className = clickedClass;
}
console.log(h1.className);
}
h1.addEventListener("click" ,handleTitleClick);
하지만 한가지 오류가 생긴다. HTML에 class가 있는 상태로 시작하게 되면 문제가 된다.
<body>
<div class ="hello">
<h1 class="sexy-font">Grab me!</h1>
</div>
.sexy-font {
font-family: -apple-system, BlinkMacSystemFont,
}
h1이 sexy-font라는 class 와 함께 시작하나, 클릭하는 event가 발생하면 class가 통째로 바뀌거나 사라진다.
다음장에서 해결 방법이 나온다.
8. ClassList , toggle 함수
classList : class들을 목록으로 작업할 수 있게 허용해줌(className은 이전의 class들을 상관하지 않고 모든 것을 교체해 버림)
toggle function : class name이 존재하는지 확인해줌(만약 class name이 존재한다면 toggle은 class name을 제거하고, class name이 존재하지 않는다면 toggle은 class name을 추가함)
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
const clickedClass = "clicked";
if(h1.classList.contains(clickedClass)) {
h1.classList.remove(clickedClass);
} else {
h1.classList.add(clickedClass);
}
console.log(h1.className);
}
h1.addEventListener("click" ,handleTitleClick);
classList 함수를 통해 class name을 보존할 수 있다.
또 한가지의 방법이 있다

toggle (class 네임 확인)
이 함수는 class name이 존재하는지 확인하고, 만약 존재한다면 class name을 제거한다.
존재하지 않는다면, class name을 추가한다.
기능적으로 우리가 바로 앞에서 구현한 코드와 동일하다.
const h1 = document.querySelector("div.hello:first-child h1");
function handleh1Click() {
h1.classList.toggle("clicked");
//함수 안 class mame
}
h1.addEventListener("click", handleh1Click);
toggle의 뜻은 켜져있을 때 누르면 잠기고, 잠기고 있을때 누르면 켜진다. (스마트폰 이라 생각)
TMI
JS가 처음이라 아직도 classname이 왜 의미가 있는지 이해가 안된다.
답을 찾으면 스토리에 바로 포스팅 하도록 하겠다.
'Front-end > javascript' 카테고리의 다른 글
크롬 앱 만들기 [바닐라 JS] Day 6 (0) | 2021.12.01 |
---|---|
크롬 앱 만들기 [바닐라 JS] Day5 (0) | 2021.11.26 |
크롬 앱 만들기 [바닐라 JS] Day4 (0) | 2021.11.25 |
크롬 앱 만들기 [바닐라 JS] Day3 (0) | 2021.11.25 |
크롬 앱 만들기 [바닐라 JS] Day1 (0) | 2021.11.23 |
댓글