JavaScript - 문제 미리보기

문제 732

hard
다음 코드의 실행 결과는?

```html
<div id="container">
<p>First</p>
<p>Second</p>
</div>

<script>
const container = document.getElementById("container");
const htmlCollection = container.getElementsByTagName("p");
const nodeList = container.querySelectorAll("p");

console.log("HTMLCollection length:", htmlCollection.length);
console.log("NodeList length:", nodeList.length);

// 새로운 p 요소 추가
const newP = document.createElement("p");
newP.textContent = "Third";
container.appendChild(newP);

console.log("After adding - HTMLCollection length:", htmlCollection.length);
console.log("After adding - NodeList length:", nodeList.length);
</script>
```
A. HTMLCollection: 2→3, NodeList: 2→3
B. HTMLCollection: 2→3, NodeList: 2→2
C. HTMLCollection: 2→2, NodeList: 2→3
D. HTMLCollection: 2→2, NodeList: 2→2

정답: B

실행 과정 분석:

1. 초기 상태:
1) HTMLCollection: 2개 (동적이므로 실시간 반영)
2) NodeList: 2개 (정적이므로 생성 시점 상태 유지)

2. 새 요소 추가 후:
1) HTMLCollection: 3개 (동적이므로 새로운 `<p>` 요소가 자동으로 포함됨)
2) NodeList: 2개 (정적이므로 변화 없음)


핵심 개념:

1) `getElementsByTagName()`은 Live HTMLCollection 반환 → DOM 변경사항 실시간 반영
2) `querySelectorAll()`은 Static NodeList 반환 → 생성 시점의 스냅샷 유지

실무 활용:

1) 동적으로 요소가 추가/제거되는 상황에서는 HTMLCollection 사용
2) 고정된 요소 집합에 대한 작업에는 NodeList가 더 안정적
3) 성능 상 NodeList가 일반적으로 더 효율적

💡 학습 팁

이 문제를 포함한 JavaScript 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.