개념이 짧고 빠르게 지나가서 매 번 들어도 기억 속에 도저히 남지 않는 것 같아서 적는 글
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
</head>
<body>
<main>
<section id="section-1" data-index="1" data-name="sec1">
<h2>섹션 1</h1>
<p>섹션 1의 paragraph</p>
</section>
<section id="section-2" data-index="2" data-name="sec2">
<h2>섹션 2</h2>
<p>섹션 2의 paragraph</p>
</section>
</main>
<script>
{
const main = document.querySelector('main')
const nodeList = main.querySelectorAll('section')
const collection = main.children
console.log('%c[nodeList]',"color: #ff0000;",nodeList);
console.log('%c[collection]',"color: #0000ff;",collection );
}
</script>
</body>
</html>


| NodeList | HTMLCollection | |
|---|---|---|
| 업데이트 | 정적,동적 | 동적 |
| 배열 메서드 | 일부 사용 가능 | Array.from으로 변환필요 |
| node 종류 | node 전체 | element node만 가져옴 |
| node | element | |
|---|---|---|
| 정의 | DOM 트리 모든 구성 단위 | 노드 중 HTML태그로 표현된 노드 |
| 종류 | 태그, 주석, 텍스트, 문서 | 오직 태그 |
| 주요 메서드 | textContent | querySelector, getAttribute |
<ul id="list">
<li>item 1</li>
<li>item 2</li>
</ul>
<button id="add">추가</button>
// HTMLCollection
const liveList = document.getElementsByTagName('li');
// NodeList
const staticList = document.querySelectorAll('li');
const button = document.getElementById('add')
button.addEventListener('click', () => {
// li 하나 추가
const newItem = document.createElement('li');
newItem.textContent = 'item 3';
document.getElementById('list').appendChild(newItem);
console.log('HTMLCollection:', liveList.length); // 3
console.log('NodeList:', staticList.length); // 2
});
li 추가가 바로 반영이 되어 3개li 추가가 반영이 안되어 2개로 남아있다