Node와 Element Node그리고 childNodes, children
node 트리 구조
위 트리구조는 노드 트리구조이다 가장 상위에 document객체가 있고 아래로 트리모양으로 node들이 분포된다.
js에서는 노드들을 불러올때 해당 노드의 하위 즉 자식 노드들을 속성을 사용하여 불러올 수 있다.
html
<section id="sec5">
<div class="box">
<input type="text" value="0" class="textx">
<input type="text" value="0" class="texty">
</div>
</section>
다음과 같은 section이 하나 주어진다.
div 노드의 자식 노드에는 input 노드가 2개 존재한다.
우리는 이 자식노드들을 children속성을 사용하여 불러올 수 있다.
js
window.addEventListener("load", function(){
var sec5 = document.querySelector("#sec5");
var box = sec5.querySelector(".box");
var input1 = box.childNodes[0];
var input2 = box.childNodes[1];
input1.value = "hello";
input2.value = "okay";
});
querselector를 사용하여 id = sec5 노드를 불러왓고 해당 노드의 box class 노드를 box에 넣어두었다.
즉
box에는 div = "box" 노드가 들어가있다.
이때
children 속성을 사용하면 해당노드의 자식노드들을 볼러올 수 있다.
해당 프로그램을 실행해 보았다.
결과
결과가 이상하다는것을 알 수 있다.
분명히 input노드에 각각 hello와 okay를 넣어주었는데 input1에 okay값이 들어가있고 input2에는 값이 존재하지도 않는다. 왜이런 현상이 일어나는것일까?
다시 위의 트리구조를 보면 #comment, #text 즉 주석과 text또한 모두 node로 취급한다.
이말은 즉
<div class = "box">뒤의 공백또한 자식 노드로 취급된다는 소리이다. 결국 배열0번에는 빈공간text가 들어가있고
배열1번에 <input type="text" value="0" class="textx"> 이 값이 들어가있는것이다.
그럼 어떻게 하면 제대로된 값을 넣고 출력할 수 있을까?
<section id="sec5">
<div class="box"><input type="text" value="0" class="textx"><input type="text" value="0" class="texty">
</div>
</section>
이렇게 빈공백 없이 노드들을 딱 붙여 코드를 작성해면 값이 제대로 기입된다.
결과
하지만 이는 가독성이 매우 좋지않은 코드이다.
이를 해결하기 위해선
children 속성을 사용하면된다.
html
<section id="sec4">
<div class="box">
<input type="text" value="0" class="textx">
<input type="text" value="0" class="texty">
</div>
</section>
js
window.addEventListener("load", function(){
var sec4 = document.querySelector("#sec4");
var box = sec4.querySelector(".box");
var input1 = box.children[0];
var input2 = box.children[1];
input1.value = "hello";
input2.value = "okay";
});
결과
결과적으로
children 속성은 태그 속성 (태그 노드)들만을 자식노드로 취하고
childNodes 속성은 주석과 text등 모든 노드를 자식으로 취하는 속성입니다.
때에따라 알맞은 속성을 사용하면 js를 유동적으로 사용할 수 있습니다.