본문 바로가기

Front-End/JavaScript

[JavaScript] 230326 학습일기

https://nomadcoders.co/javascript-for-beginners

 

바닐라 JS로 크롬 앱 만들기 – 노마드 코더 Nomad Coders

Javascript for Beginners

nomadcoders.co

노마드 코더 <바닐라 JS로 크롬 앱 만들기>로 학습한 내용을 정리하였다.


1.

document를 이용하면 JavaScript에서 html에 접근할 수 있다.

 

 

2. html 속에 있는 내용을 id로 가져오기.

 

실행할 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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <script src="app.js"></script>
    <h1 id="title">Grab me!</h1>
</body>
</html>

그리고 html을 실행하고 나서 콘솔에서 

document.getElementById("title");

을 입력해주면

 

 

3.

하 망했다.

html 파일을 liveserver 이라는 VScode 확장 프로그램을 사용해서 실행했었는데 

const title = document.getElementById('title');
title.innerText = "안녕하슈";
console.log(title);

이게 실행이 안 됐었다.

계속 저 title이 null값이라고 뜨고...

 

그런데 이 문제는 html 파일을 직접 실행히면 사라지는 문제였다.

감사하게도 어떤 분의 도웅으로 금방 해결할 수 있게 되었다.

 

문제의 원인은 무엇이었냐.

크롬 콘솔은 dom에 직접 접근해서 가져온다 .(현재 실행중인 페이지에서 바로 가져옴)

근데 js 파일로 실행하면 html 문서가 아직 로드가 안됐는데 dom에서 접근하기 때문에 그렇다.

 

일단 자바스크립트 강의 듣고 이해하는 게 급하니 이건 나중에 더 자세히 알아보자.

 

 

4.

const title = document.getElementById('title');
title.innerText = "안녕하슈";
console.log(title);
console.log(title.id);
console.log(title.className);

 

 

5.

class으로 html의 element들을 가져올 수 있다.

아래는 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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <h1 class="hello">Grab me!</h1>
    <h1 class="hello">Grab me!</h1>
    <h1 class="hello">Grab me!</h1>
    
    <script src="app.js"></script>
</body>
</html>

아래는 js 파일

const classes = document.getElementsByClassName("hello");
console.log(classes);

 

6.

tag명으로도 html속 element들을 가져올 수 있다.

아래는 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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>

    <script src="app.js"></script>
</body>
</html>

 

아래는 js 파일

const title = document.getElementsByTagName("h1");

console.log(title);

이 외에도 tag는 anchor, div, section, button 등이 있다.

 

 

7.

element를 가져오는 가장 멋진 방법은

querySelector과 querySelectorAll 이다.

 

 

  • querySelector는 element를 CSS 방식으로 검색할 수 있음.

이거는 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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>

    <script src="app.js"></script>
</body>
</html>

이거는 js 파일

const title = document.querySelector(".hello h1");
console.log(title);

hello라는 클래스 안에 있는 h1 태그를 가져와달라.

css 처럼 class 앞에 . 을 썼다.

 

남은 모든 강의에서는 document.querySelector을 사용할 예정이다.

 

 

 

또 다른 예시로는

div태그 안에 있는 h1 태그를 가져와달라고도 할 수 있다.

 

아래는 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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>

    <script src="app.js"></script>
</body>
</html>

아래는 js 파일

const title = document.querySelector("div h1");
console.log(title);

 

 

 

혹시 몰라서

const title = document.querySelector("div .hello h1");
console.log(title);
const title = document.querySelector(".hello div h1");
console.log(title);

이렇게 둘 다 해봤는데 console에서는 null이 뜬다.

이렇게는 안되는 갑다.

 

 

 

7.

querySelector을 사용할 때, hello class 안에 h1이 많을 수도 있다.

예를 들어 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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!1</h1>
    </div>
    <div class="hello">
        <h1>Grab me!2</h1>
    </div>
    <div class="hello">
        <h1>Grab me!3</h1>
    </div>

    <script src="app.js"></script>
</body>
</html>

js 파일이 아래와 같다.

const title = document.querySelector(".hello h1");
console.log(title);

그래도 실행하면

이렇게 제일 위에 거 하나밖에 안 뜬다.

querySelector는 오직 첫번재 것만 가져왔다.

 

 

다 가져오고 싶다면?

querySelectorAll을 이용해주면 된다.

const title = document.querySelectorAll(".hello h1");
console.log(title);

querySelectorAll은 이 selector 안의 조건에 부합하는 모든 element를 가져다준다.

 

 

8. querySelector의 활용

html 파일은 7번 참고

const title = document.querySelector(".hello h1:first-child");
console.log(title);

이렇게 css 문법과 같이 h1의 first-child 만 가져올 수도 있다.

 

 

9.dir

const title = document.querySelector("h1");
console.dir(title);

관련 속성들이 좌라라락 나온다.

 

 

10.

js 에서style도 바꿀 수 있다.

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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!1</h1>
    <script src="app.js"></script>
</body>
</html>

js 파일은 다음과 같다.

const title = document.querySelector("h1");
title.style.color = "blue";

 

 

11. event

클릭, h1 위로 마우스가 올라가거나, 입력을 끝내거나, 내 이름을 적거나, enter를 누르거나, wifi에서 접속 해제되거나

하는 것들이 이벤트다.

 

 

12. eventListener

event를 listen하는 것이다.

const title = document.querySelector("h1");

function handleTitleClick() {
    console.log("title was clicked");
}

title.addEventListener("click",handleTitleClick);

handleTitleClick이라는 함수를 만들고

addEventListener의 첫번째 인자로는 "click"을, 두번째 인자로는 아까 만들어두었던 handleTitleClick을 넣어주었다.

=> 클릭 시에 handleTitleClick 함수가 실행된다.

 

*주의해야할 것은 addEventListener의 두번째 인자에 함수를 넣어줄 때 ()를 넣어주면 안된다. 넣어주면 그냥 실행된다.

 

저 Grab me!1을 누르면 title was clicked 라는 메시지가 콘솔 창에 뜬다.

 

 

13.

여기에 들어가면 JavaScript 관점에서 HTML Heading Element에 대해 알려준다.

 

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement

 

HTMLElement - Web APIs | MDN

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

developer.mozilla.org

여기에 들어가면 event에 대해서도 알 수 있다.

 

 

dir를 해서도 한번 찾아보자.

const title = document.querySelector("h1");
console.dir(title);

property 앞에 on이 붙으면 event listener이다.

 

코드에서 사용할 때에는 on을 빼고 써줘야 한다.

 

 

14. mouseenter

마우스를 그 위에 올려두는 이벤트다.

const title = document.querySelector("h1");
function handleMouseEnter() {
    console.log("mouse is here!");
    title.style.color = "blue";
}
title.addEventListener("mouseenter",handleMouseEnter);

마우스를 저 Grab me!1 위에 올려놨더니 파란색으로 변하면서 콘솔에 메시지가 출력되었다.

 

 

15. mouseleave

 

mouseleave는 마우스가 떠날 때의 이벤트다.

14번에서 mouseleave를 추가해보자.

const title = document.querySelector("h1");
function handleMouseEnter() {
    console.log("mouse is here!");
    title.style.color = "blue";
}

function handleMouseLeave() {
    console.log("mouse left");
    title.style.color = "black";
}

title.addEventListener("mouseenter",handleMouseEnter);
title.addEventListener("mouseleave",handleMouseLeave);

마우스가 Grab me!1 위에 있으면 글씨가 파란색이 되고, 떠나면 다시 글씨가 검은색이 된다.

 

16. event 를 listen하는 또 다른 방법

 

on이벤트명 으로 event를 listen할 수 있다.

const title = document.querySelector("h1");
function handleTitleClick() {
    console.log("title was clicked");
    title.style.color = "blue";
}
title.onclick = handleTitleClick;

click했을 때 handleTitleClick이 실행되도록 한 것이다.

 

 

그러나 강의자는 addEventListener를 더 추천한다.

왜냐하면 나중에는 removeEventListener도 사용할 것이기 때문이다.

 

 

17. window event- resize

window가 resize(화면 크기가 바뀜)될 경우에  ---> event

화면의 색깔이 바뀌는 걸 만들어보자.

 

function handleWindowResize(){
    document.body.style.backgroundColor = "tomato";
}

window.addEventListener("resize",handleWindowResize)

이렇게 화면의 크기를 줄었더니 background-color가 바뀌었다.

 

 

18. window event - copy

function handleWindowCopy(){
    alert("copier");
}

window.addEventListener("copy", handleWindowCopy);

복사를 했더니

이렇게 alert 메시지가 뜬다.

 

 

19. window event- offline, online

와이파이가 연결되었을 때, 해제되었을 때의 이벤트도 있다.

바로 offline, online

function handleWindowOffline() {
    alert("SOS no wifi");
}
function handleWindowOnline() {
    alert("All good");
}

window.addEventListener("offline", handleWindowOffline)
window.addEventListener("online", handleWindowOnline)

 

 

 

20.

h1의 컬러를 if else를 사용해 바꿔보자.

 

if else 문 등에서 같은지 아닌지 확인하는 연산자는

===

등호 세 개다.

 

파이썬, C등의 언어에서는 하나인데 왜 자바스크립트는 굳이 셋인지는 모르겠지만 뭐 이유가 있겠지..

 

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    if (h1.style.color === "blue") {
        h1.style.color = "tomato";
    } 
    else
    {
        h1.style.color = "blue";
    }
}

h1.addEventListener("click", handleTitleClick);

 

여기서 코드를 읽기 쉽게 개선해보자.

const h1 = document.querySelector("div.hello 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);

 

강의 댓글에 hyeongjoon이라는 분께서 남겨주신 댓글에 따르면

 

currentColor는 getter로서, 최근 color값을 복사하는 역할을 한다. => const로 선언하는 것이 적절.

그리고 currentColor는 함수 내에서 const로 선언되었기 때문에 함수를 호출할 때마다 새로운 값을 받을 수 있다.

 

newColor는 setter로서, 변수에 대입된 색상값을 h1.style.color에 최종적으로 할당하는 역할을 함. => let으로 선언하는 것이 적절.

 

 

21.

JavaScript가 CSS가 아닌 HTML을 변경할 수 있도록 하는 것이 효율적이다.

js 파일은 다음과 같다.

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    h1.className = "active";
}

h1.addEventListener("click", handleTitleClick);

 

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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!1</h1>
    <script src="app.js"></script>
</body>
</html>

 

css 파일은 다음과 같다.

body {background-color: beige;}

h1 {
    color:cornflowerblue;
}

.active {
    color:tomato;
}

 

여기서 클릭하면 class가 active가 되면서

색깔이 이렇게 바뀐다.

 

 

22.

21번의 경우에서 ifelse문을 추가해서 조금 더 복잡하게 만들어보자.

 

js 파일은 다음과 같다.

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    if (h1.className=== "active") {
        h1.className = "";
    } else {
        h1.className = "active";
    }
}

h1.addEventListener("click", handleTitleClick);

 

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">
    <title>Momentum</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="hello">
        <h1>Grab me!1</h1>
    <script src="app.js"></script>
</body>
</html>

 

css 파일은 다음과 같다.

body {background-color: beige;}

h1 {
    color:cornflowerblue;
}

.active {
    color:tomato;
    transition:color .5s ease-in-out;
}

 

transition:color .5s ease-in-out

도 추가해주었다.

이걸 추가해주면 색깔이 5초동안 변한다. (파란색 -> 빨간색 될 때)

 

 

js 코드를 조금만 수정해주자.

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    const activeClass = "active";
    if (h1.className=== activeClass) {
        h1.className = "";
    } else {
        h1.className = activeClass;
    }
}

h1.addEventListener("click", handleTitleClick);

이렇게 따로 변수를 설정해주면 실수를 줄일 수 있다.

 

 

23.

기존의 방법들은 원래 있던 class를 없애고 새로운 class로 바꿔주는 거였다.

(ex.

h1.className = "active";

)

 

그런데 기존의 class를 잃기 싫을 수도 있다.

이때 해결방안이 classList다.

 

classList는 우리가 class들을 목록으로 작업할 수 있게끔 한다.

 

 

24. 

classList에서 add와 remove를 해보자

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    const activeClass = "active";
    if (h1.classList.contains(activeClass)) {
        h1.classList.remove(activeClass);
    } else {
        h1.classList.add(activeClass);
    }
}

h1.addEventListener("click", handleTitleClick);

 

코드를 살펴보자.

h1.classList.contains(activeClass)

는 h1의 classList가 "active"를 포함하고 있는지 체크하는 부분이다.

 

h1.classList.remove(activeClass);

는 h1의 classList에서 "active"를 지우는 부분이다.

 

h1.classList.add(activeClass);

는 h1의 classList에서 "active"를 추가하는 부분이다.

 

 

25.

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    const activeClass = "active";
    if (h1.classList.contains(activeClass)) {
        h1.classList.remove(activeClass);
    } else {
        h1.classList.add(activeClass);
    }
}

h1.addEventListener("click", handleTitleClick);

이 코드에서

if (h1.classList.contains(activeClass)) {
    h1.classList.remove(activeClass);
} else {
    h1.classList.add(activeClass);
}

이 부분을 아예 구현해주는 코드가 있다.

 

 

toggle은 h1의 classList에 class name이 포함되었다면 제거하고, 포함되지 않았다면 추가한다.

 

toggle을 이용해서 같은 것을 구현하는 코드를 다시 짜보면

const h1 = document.querySelector("div.hello h1");

function handleTitleClick() {
    h1.classList.toggle("active");
}

h1.addEventListener("click", handleTitleClick);

 

 

26.

toggle에 대한 설명을 읽어보면

 

토큰을 toggle한다는 것은

토글이 존재한다면 토큰을 제거하고, 존재하지 않는다면 토큰을 추가한다.

'Front-End > JavaScript' 카테고리의 다른 글

[JavaScript] Todo-List 만들기(1)  (0) 2023.03.30
[JavaScript] 230327 학습일기  (0) 2023.03.29
[JavaScript] 230324 학습일기  (1) 2023.03.25
[JavaScript] 230323 학습일기  (0) 2023.03.24
[JavaScript] 230322 학습일기  (0) 2023.03.23