HTML DOM 문서 querySelectorAll()
예시
class="example"인 모든 요소 선택:
document.querySelectorAll(".example");
아래에 더 많은 예가 있습니다.
정의 및 사용
이 querySelectorAll()
메서드는 CSS 선택기와 일치하는 모든 요소를 반환합니다.
이 querySelectorAll()
메서드는 NodeList 를 반환합니다 .
querySelectorAll()
선택자가 유효하지 않은 경우 메소드에서 SYNTAX_ERR 예외가 발생합니다 .
튜토리얼:
QuerySelector 메서드:
GetElement 메서드:
HTML DOM NodeList / HTMLCollection
HTMLCollection과 NodeList의 차이점
NodeList 와 HTMLCollection 은 모두 문서에서 추출한 노드(요소)의 배열과 유사한 컬렉션(목록)입니다 . 노드는 인덱스 번호로 액세스할 수 있습니다. 인덱스는 0에서 시작합니다.
두 개체 모두 목록의 요소 수를 반환 하는 길이 속성을 가지고 있습니다.
HTMLCollection은 라이브 컬렉션입니다 . DOM의 목록에 <li> 요소를 추가하면 HTMLCollection의 목록도 변경됩니다.
NodeList는 정적 컬렉션입니다 . DOM의 목록에 <li> 요소를 추가해도 NodeList의 목록은 변경되지 않습니다.
getElementsByClassName()
및 메서드 는 getElementsByTagName()
HTMLCollection을 반환합니다.
querySelector()
및 메서드 는 querySelectorAll()
NodeList를 반환합니다.
통사론
document.querySelectorAll(CSS selectors)
매개변수
Parameter | Description |
CSS selectors | Required. One or more CSS selectors. CSS selectors select HTML elements based on id, classes, types, attributes, values of attributes etc. For a full list, go to our CSS Selectors Reference. For multiple selectors, separate each selector with a comma (See "More Examples"). |
반환 값
유형 | 설명 |
물체 | CSS 선택기와 일치하는 요소가 있는 NodeList . 일치하는 항목이 없으면 null 반환됩니다. |
더 많은 예
첫 번째 <p> 요소에 배경색을 추가합니다.
const nodeList= document.querySelectorAll("p");
nodeList[0].style.backgroundColor = "red";
class="example"인 첫 번째 <p> 요소에 배경색을 추가합니다.
const nodeList = document.querySelectorAll("p.example");
nodeList[0].style.backgroundColor = "red";
class="example"인 요소 수:
let numb = document.querySelectorAll(".example").length;
class="example"을 사용하여 모든 요소의 배경색을 설정합니다.
const nodeList = document.querySelectorAll(".example");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
모든 <p> 요소의 배경색을 설정합니다.
let nodeList = document.querySelectorAll("p");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
"target" 속성을 사용하여 모든 <a> 요소의 테두리를 설정합니다.
const nodeList = document.querySelectorAll("a[target]");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.border = "10px solid red";
}
부모가 <div> 요소인 모든 <p> 요소의 배경색을 설정합니다.
const nodeList = document.querySelectorAll("div > p");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
모든 <h3>, <div> 및 <span> 요소의 배경색을 설정합니다.
const nodeList = document.querySelectorAll("h3, div, span");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
브라우저 지원
document.querySelectorAll()
DOM 레벨 3(2004) 기능입니다.
모든 브라우저에서 완벽하게 지원됩니다.
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |