728x90
Document.querySelector()는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element(요소)를 반환한다. 일치하는 요소가 없으면 null을 반환한다.
querySelector 은 Element를 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
'Front-end School > JS' 카테고리의 다른 글
[Javascript]원시형과 참조형 (0) | 2023.01.12 |
---|---|
[Javascript] 이벤트 버블링(bubbling)이란? 버블링 중단하기 (0) | 2022.02.28 |
[Javascript] - promise 메서드 then, catch, finally (1) | 2022.02.25 |
[Javascript] DOM 기초 - HTML in Javascript (0) | 2022.02.18 |
[Javascript] DOM 기초 - Document 알아보기 (0) | 2022.02.16 |