티스토리 뷰

Javascript

[js&css] Dom and Array 문제풀이

심재철 2019. 6. 7. 09:49
<div id="container">
	<div class="child">...</div>
	<div class="child">...</div>
	<div class="child">...</div>
	<div class="child">...</div>
</div>  
let parentDiv = document.getElementById('container')
let childDivs = document.querySelectorAll('.child')
let childDivsAgain = document.getElementsByClassName('child')

// question 1.
// 여기에 childDivs, childDivsAgain가 array인지 아닌지 판별하는 코드를 작성하세요.

// length 결과 A
console.log(childDivs.length); //=> 4
console.log(childDivsAgain.length); //=> 4

// 새로운 .child 추가
var newDiv = document.createElement('div');
newDiv.className = 'child';
parentDiv.appendChild(newDiv);

// length 결과 B
console.log(childDivs.length); //=> 4
console.log(childDivsAgain.length); //=> 5

// question 2.
// length 결과 B에서 childDivs.length값과 childDivsAgain.length값이 다른 이유를 간략히 서술하세요.

document.querySelectorAll 메서드는 정적 NodeList를 반환한다. 반면에 document.childNodes() 메서드는 동적 NodeList를 반환한다. 정적 노드리스트란 말은 쿼리셀렉터로 어떤 돔 엘리먼트를 js로 가져왔다고 했을때 그 후에 DOM에 추가되는 엘리먼트에 대해서는 업데이트가 진행되지 않는다는 뜻이고, 동적 노드 리스트라는것은 돔에 요소가 추가 되면 그 추가된 요소까지 컬렉션에 반영 된다는 뜻이다.

 

var parent = document.getElementById('parent');

var child_nodes = parent.childNodes;

console.log(child_nodes.length); // let's assume "2"

parent.appendChild(document.createElement('div'));

console.log(child_nodes.length); // should output "3"

 

getElementsByClassName 메서드는 HTMLCollection이라는것을 반환하는데 이것은 동적 컬렉션이다.

결국엔 childDivs와 childDivsAgain에 들어간 두개의 객체 모두 배열은 아니다.

 

https://jsfiddle.net/z8wkqe1r/5/

 

Edit fiddle - JSFiddle

 

jsfiddle.net

// length 결과 B에서 childDivs.length값과 childDivsAgain.length값이 다른 이유를 간략히 서술하세요.
// querySelectorAll 메서드는 정적 노드리스트를 반환하지만 getElementsByClassName 메서드는 동적 HTMLCollection을 반환하기 때문이다. 따라서 새롭게 돔에 엘리먼트가 추가 되었을때 childDivs의 정적 노드리스트에는 그 엘리먼트가 동적으로 업데이트 되지 않았지만 childDivsAgain은 동적 HTMLCollection 객체 이므로 새로운 돔 엘리먼트가 컬렉션에 추가 되었다.

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함