[Javascript] 노마드 코더 - 바닐라 JS로 크롬 앱 만들기 (1) Javascript, HTML, CSS 기초

김지원·2022년 10월 13일
0

Frontend

목록 보기
2/27

✨Javascript 과 브라우저

❓ Javascript가 브라우저를 어떻게 움직이게 하는가?

Javascript를 사용하는 이유는 HTML 과 상호작용 하기 위해서이다.
즉, HTML의 Element들은 Javascript를 통해 변경하고 읽을 수 있다.

브라우저의 핵심 object, document

브라우저에 이미 존재하는 object이다.

> console.dir('document')

> document.title  // JavaScript로 HTML에 접근하고 읽을 수 있다.
"Momentum"

> document.title = "HI" // JavaScript로 HTML을 변경할 수 있다.
"HI" 

✨HTML in Javascript

❓ JavaScript로 정보를 가져올 수 있는 방법

JavaScript는 HTML의 object를 보여준다.

getElementById()

const title = document.getElementById("title");  // id값으로 element 가져오기
// <h1 id="title"> Grab me! </h>

title.innerText="Got you!";  // JavaScript로 HTML 항목 변경 가능

getElementsByClassName()

classname으로 Element들을 가져올 수 있다.
많은 element를 한번에 가지고 와야하는 경우 사용한다.

// <h1 class="hello"> hello </h>
// <h1 class="hello"> hello </h>
// <h1 class="hello"> hello </h>
// <h1 class="hello"> hello </h>
// <h1 class="hello"> hello </h>

const hellos = document.getElementsByClassName("hello");    
console.log(hellos) // 모든 h1 elements가 배열로 나온다. 

getElementsByClassName()

Tagname으로 Element들을 가져올 수 있다.
많은 element를 한번에 가지고 와야하는 경우 사용한다.

// <div class="hello">
//	<h1> Grab me! </h1>
// </div>

const hellos = document.getElementsByTagName("h1");    
console.log(hellos) // 모든 h1 elements가 배열로 나온다. 

가장 추천하는 방식 querySelector(), querySelectorAll()

element를 CSS 방식으로 검색할 수 있다.
querySelector()는 해당되는 element가 1개 이상일 경우, 첫 번째 element만 가져온다.
모두 가져오고 싶다면 querySelectorAll() 사용하면 된다. 조건에 부합하는 모든 element를 배열로 가져온다.

# <div class="hello">
#	<h1> Grab me! </h1>
# </div>

const hellos = document.querySelector(".hello h1");    
const hellos = document.querySelector("div h1");  
profile
Make your lives Extraordinary!

0개의 댓글