HTMLCollection과 NodeList가 도대체 뭔지..
이번에도 gpt를 사용해서 정리해본다.
1. HTMLCollection과 NodeList 공통점
- DOM 요소의 집합
- 배열처럼 인덱스로 요소 접근 가능
- `length` 프로퍼티로 요소의 개수 확인 가능
2. HTMLCollection과 NodeList 차이점
구분 | HTMLCollection | NodeList |
생성 메서드 | `getElementsByClassName()` `getElementsByTagName()` `document.forms` `form.elements` `document.image` `document.links` `document.anchors` |
`querySelectAll()` `childNodes` |
Live 여부 | O (DOM 변경 시 자동 업데이트) | X 대부분 Static (DOM 변경에 영향 없음) (단, `childNodes`는 Live) |
요소 타입 | Element 노드만 포함 | 모든 노드(Element, Text, Comment 등 ) 포함 |
메서드 | `item()`, `nameItem()` | `forEach()`, `entries()`, `keys()` 등 배열 메서드 사용 가능 |
이름으로 접근 | O (`name` 속성 사용) | X |
2-1. 상세 설명
2-1-1. HTMLCollection
- Live Collection : DOM이 변경되면 자동으로 컬렉션이 업데이트
const items = document.getElementsByClassName('item');
console.log(items); // 3
// 새로운 요소 추가
const newItem = document.createElement('div');
newItem.className = 'item';
document.body.appendChild(newItem);
console.log(items.length); // 4 (자동업데이트)
- 이름으로 접근 가능 : `name` 속성을 가진 요소는 이름으로 직접 접근 가능
<form name="myForm">
<input type="text" name="username">
</form>
const form = document.forms.myForm;
console.log(form.username); // name="username"인 input 요소
2-1-2. NodeList
- 대부분 Static : `querySelectorAll()` 로 생성된 NodeList는 DOM 변경을 반영하지 않음
const items = document.querySelectorAll('.item');
console.log(items.length); // 3
// 새로운 요소 추가
const newItem = document.createElement('div');
newItem.className = 'item';
document.body.appendChild(newItem);
console.log(items.length); // 3 (변경없음)
/* Live NodeList 예외 - childNodes */
const liveNodes = docuement.body.childNodes;
console.log(liveNodes); // 초기 값
// DOM 변경 시
document.body.appendChild(document.createElement('div'));
console.log(liveNodes.length); // 1 증가 (업데이트됨)
- 배열 메서드 지원 : `forEach()`, `map()`, `filter()` 등 사용 가능
- 모든 노드 타입 포함 : 텍스트 노드, 주석 노드도 포함 할 수 있다.
<div class="box">
<!-- 주석 -->
Hello World!
</div>
const nodes = documents.querySelector('.box').childNodes;
console.log(nodes); // [ #text, <!-- 주석 -->, #text ]
예외) getElementsByName
getElements~ 가 붙어있어서 HTMLCollection이라고 생각하지만 NodeList 이다.
- 다른 "getElements~" 계열과 달리 유일하게 NodeList를 반환.
- 하지만 Live여부는 Static 으로 DOM이 바뀌어도 자동으로 바뀌지 않는다.
- 실제로는 NodeList이지만 HTMLCollection과 비슷하게 인덱스로 접근 가능하며, name 속성값으로도 접근 가능
<input type="text" name="user">
<input type="text" name="user">
const nodes = document.getElementsByName('user');
console.log(nodes instanceof NodeList); // true
console.log(nodes instanceof HTMLCollection); // false
console.log(nodes.length); // 2
nodes[0].value = 'hello';