본문 바로가기
Dev/JavaScript

[노마드코더] 바닐라 JS로 크롬 앱 만들기 - #3.2

by MICOSA 2021. 11. 28.

#3.2 Searching For Elements

 

 

개념

id가 사용하기 편리하지만, 보통 className을 사용하거나 둘 다 사용함.

 

<!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 App</title>
</head>
<body>
    <h1 class="hello">Grab me!</h1>
    <h1 class="hello">Grab me!</h1>
    <h1 class="hello">Grab me!</h1>
    <h1 class="hello">Grab me!</h1>
    <h1 class="hello">Grab me!</h1>
</body>
</html>

 

const hellos = document.getElemetByClassName("hello");

console.log(hellos);

 

결과값

 

 

 


 

대부분의 경우에는 class name을 모든 곳에 추가하지는 않음.

 

<!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 App</title>
</head>
<body>
    <div class="hello">
    	<h1>Grab me!</h1>
    </div>
</body>
</html>
const title = document.getElemetByTagName("h1");

console.log(title);

결과값

위의 결과값은 우리가 원하는 것이 아님.

title로 무엇인가를 할 수 없기 때문.

title이 title object 자체가 아니고 array이기 때문에 위와 같은 결과값이 나옴.

element를 가지고 오는 가장 멋진 방법은 querySelector와 querySelectorAll임.

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

즉, hello란 class 내부에 있는 h1을 가지고 올 수 있다는 것을 의미함.

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

 

 

 


 

querySeletor /  querySeletorAll

 

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

console.log(title);

결과값

위와 같이 CSS처럼 쓸 수 있음.

CSS selector이기에 hello 앞에 .을 써줌.

 

 

 

 

hello의 h1이 다수일 때, 결과값은 어떻게 나올까?

<!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 App</title>
</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>
</body>
</html>

 

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

console.log(title);

결과값

 

결과로 첫번째 element 하나만 가져오는 것을 확인할 수 있음.

이렇듯 querySelector를 사용할 때, hello class 안에 h1이 많을 수 있음.

모두를 가져오기 위해선  querySeletorAll 을 사용해야 함.

 

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

console.log(title);

결과값

 

querySeletorAll은 세개의 h1이 들어있는 array를 가져오는 것을 확인할 수 있음.

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

 

 

 

참고

아래 코드는 서로 결과 값이 같음.

const title = document.querySeletor("#hello");
const title = document.getElementById("hello");

 

 

 

 

 

댓글