JS 4.2 · 4부. 브라우저와 DOM

요소 선택하기

querySelector 로 화면의 요소를 찾습니다.

예상 학습 시간 14분 실행 단추가 있는 예제는 고쳐서 실행해 볼 수 있습니다 난이도 입문
개념 설명

먼저 찾아야 다룰 수 있습니다

화면의 무언가를 바꾸려면 그것을 먼저 찾아야 합니다. 찾는 방법은 둘입니다. 둘 다 앞 단원의 선택자를 그대로 사용합니다.

  • querySelector — 맞는 것 하나를 찾습니다. 여럿이면 첫 번째입니다.
  • querySelectorAll — 맞는 것 전부를 찾습니다.

둘 다 document 에 붙여 씁니다. document 는 지금 열려 있는 화면 전체입니다.

최소 예제 · 편집 가능

하나 찾기

script.js
const title = document.querySelector("h1");

console.log(title.textContent);
console.log(title.tagName);
출력
상품 목록 H1

textContent 는 그 안의 글자입니다. 다음 단원에서 바꾸는 방법을 다룹니다.

상세 사용법

전부 찾기

script.js
const items = document.querySelectorAll(".item");

console.log(items.length);

items.forEach(item => console.log(item.textContent));
출력
3 연필 공책 지우개

돌려받은 것은 배열이 아닙니다. lengthforEach 는 되지만 map 이나 filter 는 없습니다. 필요하면 배열로 바꿔야 합니다 — 아래에서 다룹니다.

상세 사용법

못 찾으면

script.js
const missing = document.querySelector("#없는것");
const empty = document.querySelectorAll(".없는것");

console.log(missing);
console.log(empty.length);
출력
null 0

querySelectornull, querySelectorAll빈 목록입니다. 오류가 아닙니다. 못 찾은 것을 그대로 다루면 그때 오류가 납니다.

상세 사용법

배열로 바꿔 다루기

3부의 방법을 사용하려면 배열로 바꿉니다. 3.7 의 스프레드가 그대로 쓰입니다.

script.js
const items = [...document.querySelectorAll(".item")];

const names = items.map(item => item.textContent);

console.log(names);
console.log(names.filter(name => name.length === 2));
출력
["연필", "공책", "지우개"] ["연필", "공책"]
상세 사용법

요소 안에서 다시 찾기

document 대신 찾은 요소에 붙이면 그 안에서만 찾습니다. 화면이 커질수록 이 방법이 안전합니다.

script.js
const right = document.querySelector("#right");

console.log(document.querySelector(".name").textContent);
console.log(right.querySelector(".name").textContent);
출력
왼쪽 오른쪽
흔한 실수

처음에 자주 걸리는 것

1. 못 찾은 것을 그대로 다룹니다

null 에서 속성을 읽으면 오류가 납니다. 선택자 철자를 확인하거나, 6.5 의 ?. 로 안전하게 다룹니다.

TypeError: Cannot read properties of null (reading 'textContent')
2. querySelectorAll 에 map 을 사용합니다

배열이 아니라 없습니다. [...목록] 으로 배열로 바꾸세요.

TypeError: items.map is not a function
3. 여럿을 기대하고 querySelector 를 사용합니다

querySelector 는 첫 번째 하나만 돌려줍니다. 전부가 필요하면 querySelectorAll 입니다.

실습 문제

직접 해보기

1. 몇 개인지 세기 난이도 하

위 예제의 코드를 고쳐, 목록에 든 항목이 몇 개인지와 마지막 항목의 글자를 출력하세요.

const items = document.querySelectorAll(".item"); console.log(items.length); console.log(items[items.length - 1].textContent);
2. 글자를 모아 한 줄로 난이도 중

목록의 글자를 모아 연필, 공책, 지우개 형태의 한 줄로 출력하세요.

배열로 바꾼 뒤 mapjoin 을 잇습니다(3.5).
const names = [...document.querySelectorAll(".item")] .map(item => item.textContent) .join(", "); console.log(names);
요약

이 단원의 정리

  • querySelector 는 하나, querySelectorAll 은 전부를 찾습니다.
  • 선택자는 4.1 에서 본 것을 그대로 사용합니다.
  • 못 찾으면 null 이나 빈 목록입니다. 오류가 아닙니다.
  • querySelectorAll 의 결과는 배열이 아닙니다. [...목록] 으로 바꿉니다.
  • 찾은 요소에 붙이면 그 안에서만 다시 찾습니다.