부트캠프/Front
[HTML] HTML Collection
혀니hyun
2025. 3. 12. 16:47
chatGPT에게 HTML Collection에 대해 질문했다.
꽤나 이해하기 쉽게 답변해 주었다.
📌 HTMLCollection vs 배열(Array)
HTMLCollection은 자바스크립트에서 HTML 요소들의 집합을 나타내는 특수한 객체로, 배열과 몇 가지 중요한 차이점이 있습니다.
1️⃣ HTMLCollection vs 배열 차이점
특성 | HTMLCollection | 배열(Array) |
---|---|---|
자료구조 | 유사 배열 객체 | 일반 배열 |
인덱스 접근 | collection[0] 가능 |
array[0] 가능 |
forEach 사용 | ❌ 직접 사용 불가 (Array.from() 필요) |
✅ 바로 사용 가능 |
실시간 반영 | ✅ 문서 변경 시 자동 업데이트 | ❌ 변경되지 않음 (정적인 값) |
메서드 | .item() , .namedItem() 등 일부 지원 |
.push() , .map() , .filter() 등 다수 지원 |
2️⃣ HTMLCollection은 유사 배열 객체
const divs = document.getElementsByTagName('div');
console.log(divs); // HTMLCollection(3) [div, div, div]
console.log(Array.isArray(divs)); // false
console.log(divs instanceof Array); // false
- `HTMLCollection`은 배열이 아니므로 `forEach()` 같은 배열 메서드를 직접 사용할 수 없습니다.
- `Array.from(divs)` 또는 `[...divs]` 를 사용하면 배열로 변환할 수 있습니다.
3️⃣ HTMLCollection은 실시간 반영
const divs = document.getElementsByTagName('div');
console.log(divs.length); // 예: 3
document.body.appendChild(document.createElement('div')); // 새로운 div 추가
console.log(divs.length); // 4 (자동 업데이트!)
- `HTMLCollection`은 DOM 변경이 반영되지만, 배열은 처음 가져온 값이 유지됩니다.
4️⃣ HTMLCollection을 배열처럼 사용하려면?
const divsArray = Array.from(document.getElementsByTagName('div'));
divsArray.map(div => console.log(div.innerText)); // 배열 메서드 사용 가능
✅ 결론
HTMLCollection
은 DOM 요소를 실시간으로 반영하는 유사 배열 객체이다.- 배열 메서드를 사용하려면
Array.from()
또는[...collection]
변환이 필요하다. document.getElementsByTagName()
,document.getElementsByClassName()
등이 반환하는 객체가HTMLCollection
이다.
이제 HTMLCollection과 배열의 차이를 확실히 이해할 수 있겠죠? 🚀