본문 바로가기
Front-end School/JS

[Javascript] 요소 찾기 querySelector, querySelectorAll

by .LUKA 2022. 2. 26.
728x90

Document.querySelector()는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element(요소)를 반환한다. 일치하는 요소가 없으면 null을 반환한다.

querySelectorElement를 CSS방식으로 쉽게 검색할 수 있다.

 

기본 구문은 다음과 같다.

document.querySelector(selectors);

 

사용 예시를 들기 위해 HTML을 작성해준다.

 

<!DOCTYPE html>
<html lang="ko">
<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>document</title>
</head>
<body>
    <div class="luka">
        <h1>안녕하세요</h1>
    </div>
    <script src="index.js"></script>
</body>
</html>

 

luka라는 클래스 네임을 가진 div 태그를 지정해보려고 한다.

 

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

 

코드를 실행해보면 알맞게 div태그를 잘 불러온 것을 볼 수 있다.

코드 실행 결과

 

그렇다면 div태그 내부의 h1 태그를 불러올때는 어떻게 할까?

 

const title = document.querySelector(".luka h1"); //luka 클래스 내부의 h1 태그라는 의미가 된다.
console.log(title);

 

코드 실행 결과


querySelectorAll 이란 document 내부의 모든 해당 선택자 요소를 모두 불러온다.

 

<!DOCTYPE html>
<html lang="ko">
<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>document</title>
</head>
<body>
    <div class="luka">
        <h1>안녕하세요</h1>
        <h1>안뇽하세요</h1>
        <h1>안냥하세요</h1>
    </div>
    <script src="index.js"></script>
</body>
</html>

 

위와 같이 div 태그 내부에 h1 태그 3개를 만들어 줬다.

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

결과를 한번 예상해보자

 

코드 실행 결과

이유는 querySelector 은 첫번째 요소만을 반환하기 때문이다.

그래서 이것을 다음과 같이 querySelectorAll로 바꾸어 준다면?

 

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

 

코드 실행 결과

다음과 같이 어레이 형태로 h1태그를 모두 불러온 것을 확인할 수 있다.

728x90