querySelector는 DOM에서 CSS 선택자를 사용해서 요소를 찾는 메서드이며, 브라우저가 제공하는 Document API 입니다.
#id, .class, tag, div > pnull 을 반환합니다.document.querySelector(선택자)
왜
undefined가 아닌null을 반환할까?
null은 값이 없다는 명시적인 의미를 갖고 있고,undefined는 변수에 값이 할당되지 않았거나 정의되지 않은 경우를 의미한다.
<div class="box">첫 번째 박스</div>
<div class="box">두 번째 박스</div>
<p id="message">안녕하세요</p>
// ID 선택자
const msg = document.querySelector("#message");
console.log(msg.textContent); // "안녕하세요"
// 클래스 선택자
const firstBox = document.querySelector(".box");
console.log(firstBox.textContent); // "첫 번째 박스"
// 태그 선택자
const pTag = document.querySelector("p");
console.log(pTag.textContent); // "안녕하세요"
.box 처럼 여러 개가 있어도 첫 번째 요소만 가져옵니다.querySelector → 매칭되는 첫 번째 요소만 반환합니다.quertySelectorAll → 매칭되는 모든 요소를 반환합니다.querySelector로 통일할 수 있습니다.getElementsById, getElementsByClassName 등document.querySelector("div > p.red")