📌Language/JavaScript

자바스크립트로 크롬 앱 만들기 - 노마드 코더 클론코딩 #4 JS에서 HTML element 가져오고 검색하는 방법

hellohailie 2022. 4. 7. 21:26

자바스크립트와 HTML 의 상관관계!

 

 

브라우저에서 그냥 사용할 수 있는 'document'라는 object.


document의 함수 중에는 getElementById 라는 함수가 있는데, 이 함수가 HTML에서 id를 통해 element를 찾아준다.

ex)아래 예제에서는 title 이라는 id를 찾고있는거다. 

만약 title 이란 id를 가진 element가 없으면 아무것도 찾지 못하는거다. 

 


element를 찾고 나면, JS로 해당 HTML의 무엇이든 바꿀 수 있다.


ex. element의 innerText를 바꾼다던가 (title.innerText = "Got you!";)
id, className 등을 가져 올 수 있음. (cosole.log(title.id);)

 

 

 <body> 
     <h1 class= "hi" id="title">Grab me!</h1>
    <script src="app.js"></script>
 </body>
const title = document.getElementById("title");

title.innerText = "Got you!";

console.log(title.id);
console.log(title.className);

[Log] title (app.js, line 5)
[Log] hi (app.js, line 6)

 

 


HTML에 정의된 id가 JS에서와 같지 않다면 당연히 아무것도 찾지 못한다.  

 

 

ex)      <h1 class= "hello " id="something">Grab me!</h1>

const title = document.getElementById("something");

 

근데 실행하면 이런 오류뜸!

==> 아무것도 없는 (null) 값에 접근하려고 해서 이런 오류가 뜬거다. 

즉, something 이라는 id를 가진 항목이 없기 때문이다. 

 

HTML 보면 hello라는 class만 있으니까!!

 

그러니까 title은 null 인데 나는 지금 null의 innerText를 변경하려고 한거다.

 

 <!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>hello hailie!</title>
 </head>
 <body> 
     <h1 class= "hello " id="something">Grab me!</h1>
    <script src="app.js"></script>
 </body>
 </html>

 

const title = document.getElementById("something");

title.innerText = "Got you!";

console.log(title.id);
console.log(title.className);

 

 

 


hello class를 사용하는 방법

 

- getElementsByClassName() : 많은 element를 가져올때 씀(array를 반환)

 

 

 

 


 

- getElementsByTagName() : name을 할당할 수 있음(array를 반환)

 

 


- querySelector : element를 CSS selector방식으로 검색할 수 있음 (ex. h1:first-child)

 

 

hello라는 class 내부에 있는 h1을 가지고 올 수 있다.

그래서 우리는 CSS selector를 사용해서 class hello를 찾고, 그 안에 있는 h1을 가져와달라고 할거야.

 

👇

 (". hello h1") 인 이유는 CSS selector이기 때문이다!

 

참고로 getElementsByClassName("hello")라고만 쓴 이유는 JS에서 우리가 classname을 넘겨준다는 것을 알기 때문이다.

 

querySelector에는 hello가 classname이라는 것과 그 안의 h1을 명시해줘야한다. 

 


querySelector 는 단하나의 element를 return한다. 

 

첫번째 것만 출력됨.

 

 

근데 화면에는 이렇게 나옴.

 

 


 

querySelectorAll = selector 안의 조건에 부합하는 모든 element를 가져온다. 

 

(만약 3가지를 모두 가지고 오고 싶다면 querySelectorAll을 사용하면 된다. )

 

 

그럼 이런 array가 나온다. 

 

 


same

같은 코드!!