DOM Elementツリー

会社の勉強会でDOMをあつかった。

ドキュメントツリーについて、期待通りの動作をしなかったのでφ(..)メモメモ

dom.html

<html>
	<head>
		<title>DOM Tree</title>
		<script src="./dom.js" type="text/javascript">
		</script>
	</head>
	<body onload="domTree()">
		<h1>DOM Tree</h1>
		<p>
			This document is <i>DOM</i> sample.
		</p>
	</body>
</html>

dom.js

'use strict';

function domTree() {
	var node = document.documentElement;
	var children = node.childNodes;
	var i, size;
	
	size = children.length;
	
	for (i = 0; i < size; i++) {
		console.log('node[' + i + '] (' + children[i]
			+ ') ' + children[i].innerHTML);
	}
}

実行結果

node[0] ([object HTMLHeadElement]) <title>DOM Tree</title> <script src="./dom.js" type="text/javascript"> </script>
node[1] ([object Text]) undefined
node[2] ([object HTMLBodyElement]) <h1>DOM Tree</h1> <p> This document is <i>DOM</i> sample. </p> 

nodeの子要素としてはhead,bodyの2つだと思っていたのだが、期待に反して3つある。謎のテキスト要素はどこから来た?
色々試すと、次のhtmlなら子要素は2つになる。

<html>
	<head>
		<title>DOM Tree</title>
		<script src="./dom.js" type="text/javascript">
		</script>
	</head><body onload="domTree()">
		<h1>DOM Tree</h1>
		<p>
			This document is <i>DOM</i> sample.
		</p>
	</body>
</html>

間のホワイトスペースが謎のText要素だったわけ。

まぁ普通はdocument.bodyでbody要素を取得するので余り気にしないことにしよう。