요소 선택하기
querySelector 로 화면의 요소를 찾습니다.
먼저 찾아야 다룰 수 있습니다
화면의 무언가를 바꾸려면 그것을 먼저 찾아야 합니다. 찾는 방법은 둘입니다. 둘 다 앞 단원의 선택자를 그대로 사용합니다.
querySelector— 맞는 것 하나를 찾습니다. 여럿이면 첫 번째입니다.querySelectorAll— 맞는 것 전부를 찾습니다.
둘 다 document 에 붙여 씁니다.
document 는 지금 열려 있는 화면 전체입니다.
하나 찾기
const title = document.querySelector("h1"); console.log(title.textContent); console.log(title.tagName);
textContent 는 그 안의 글자입니다. 다음 단원에서
바꾸는 방법을 다룹니다.
전부 찾기
const items = document.querySelectorAll(".item"); console.log(items.length); items.forEach(item => console.log(item.textContent));
돌려받은 것은 배열이 아닙니다.
length 와 forEach 는
되지만 map 이나
filter 는 없습니다. 필요하면 배열로 바꿔야
합니다 — 아래에서 다룹니다.
못 찾으면
const missing = document.querySelector("#없는것"); const empty = document.querySelectorAll(".없는것"); console.log(missing); console.log(empty.length);
querySelector 는
null, querySelectorAll 은
빈 목록입니다. 오류가 아닙니다. 못 찾은 것을 그대로 다루면 그때 오류가
납니다.
배열로 바꿔 다루기
3부의 방법을 사용하려면 배열로 바꿉니다. 3.7 의 스프레드가 그대로 쓰입니다.
const items = [...document.querySelectorAll(".item")]; const names = items.map(item => item.textContent); console.log(names); console.log(names.filter(name => name.length === 2));
요소 안에서 다시 찾기
document 대신 찾은 요소에 붙이면 그 안에서만
찾습니다. 화면이 커질수록 이 방법이 안전합니다.
const right = document.querySelector("#right"); console.log(document.querySelector(".name").textContent); console.log(right.querySelector(".name").textContent);
처음에 자주 걸리는 것
null 에서 속성을 읽으면 오류가 납니다. 선택자
철자를 확인하거나, 6.5 의 ?. 로 안전하게
다룹니다.
TypeError: Cannot read properties of null (reading 'textContent')
배열이 아니라 없습니다. [...목록] 으로 배열로
바꾸세요.
TypeError: items.map is not a function
querySelector 는 첫 번째 하나만 돌려줍니다.
전부가 필요하면 querySelectorAll 입니다.
직접 해보기
위 예제의 코드를 고쳐, 목록에 든 항목이 몇 개인지와 마지막 항목의 글자를 출력하세요.
목록의 글자를 모아 연필, 공책, 지우개 형태의 한
줄로 출력하세요.
map 과 join 을 잇습니다(3.5).이 단원의 정리
querySelector는 하나,querySelectorAll은 전부를 찾습니다.- 선택자는 4.1 에서 본 것을 그대로 사용합니다.
- 못 찾으면
null이나 빈 목록입니다. 오류가 아닙니다. querySelectorAll의 결과는 배열이 아닙니다.[...목록]으로 바꿉니다.- 찾은 요소에 붙이면 그 안에서만 다시 찾습니다.