라이브러리
[JAVASCRIPT] document.querySelectorAll(selector) - CSS 선택자로 요소 목록(NodeList) 선택
document.querySelectorAll(selector)
`document.querySelectorAll(selector)`는 HTML 문서 내에서 선택자에 매치되는 모든 요소를 반환하는 메서드입니다. 이 메서드는 NodeList를 반환하며, NodeList는 HTMLCollection과 유사하지만 NodeList는 DOM 노드의 변경에 반응하지 않습니다.
# 선택자
선택자는 CSS 선택자와 유사하며, 다음과 같은 형태를 가집니다.
- `#id` : id 선택자
- `.class` : class 선택자
- `tag` : 태그 선택자
- `tag.class` : 태그와 class 선택자
- `tag#id` : 태그와 id 선택자
- `tag.class#id` : 태그, class, id 선택자
# 예제
#hostingforum.kr
javascript
// id 선택자
const idElement = document.querySelectorAll('#myId');
console.log(idElement); // NodeList(1) [ ]
// class 선택자
const classElement = document.querySelectorAll('.myClass');
console.log(classElement); // NodeList(2) [ , ]
// 태그 선택자
const tagElement = document.querySelectorAll('div');
console.log(tagElement); // NodeList(3) [ , , ]
// 태그와 class 선택자
const tagClassElement = document.querySelectorAll('div.myClass');
console.log(tagClassElement); // NodeList(1) [ ]
// 태그와 id 선택자
const tagIdElement = document.querySelectorAll('div#myId');
console.log(tagIdElement); // NodeList(1) [ ]
// 태그, class, id 선택자
const allElement = document.querySelectorAll('div.myClass#myId');
console.log(allElement); // NodeList(1) [ ]
# NodeList
NodeList는 HTMLCollection과 유사하지만 NodeList는 DOM 노드의 변경에 반응하지 않습니다. NodeList는 다음과 같은 메서드를 지원합니다.
- `item(index)` : 특정 인덱스의 요소를 반환합니다.
- `length` : NodeList의 길이를 반환합니다.
- `forEach(callback)` : NodeList의 각 요소에 대해 callback 함수를 호출합니다.
# 예제
#hostingforum.kr
javascript
// NodeList의 item 메서드
const nodeList = document.querySelectorAll('div');
console.log(nodeList.item(0)); //
// NodeList의 length 메서드
console.log(nodeList.length); // 3
// NodeList의 forEach 메서드
nodeList.forEach((element) => {
console.log(element); // NodeList의 각 요소를 출력합니다.
});
# NodeList의 변경에 반응하지 않는다는 점
NodeList는 DOM 노드의 변경에 반응하지 않습니다. 예를 들어, NodeList를 사용하여 요소를 삭제한 후 NodeList의 길이를 출력하면 여전히 이전 길이를 출력합니다.
# 예제
#hostingforum.kr
javascript
// NodeList의 변경에 반응하지 않는다는 점
const nodeList = document.querySelectorAll('div');
console.log(nodeList.length); // 3
// NodeList의 요소를 삭제
const divElement = document.querySelector('div');
divElement.remove();
// NodeList의 길이를 출력
console.log(nodeList.length); // 여전히 3
# NodeList를 Array로 변환하는 방법
NodeList를 Array로 변환하는 방법은 다음과 같습니다.
#hostingforum.kr
javascript
// NodeList를 Array로 변환
const nodeList = document.querySelectorAll('div');
const array = Array.from(nodeList);
console.log(array); // Array(2) [ , ]
# NodeList를 Array로 변환하는 방법 2
NodeList를 Array로 변환하는 방법은 다음과 같습니다.
#hostingforum.kr
javascript
// NodeList를 Array로 변환
const nodeList = document.querySelectorAll('div');
const array = [...nodeList];
console.log(array); // Array(2) [ , ]
- 목록
댓글목록
등록된 댓글이 없습니다.