Child elements

There are several ways to obtain element children.

childNodes

An element keeps references to children in childNodes array-like property.

All nodes are referenced, including whitespace ones (excepts IE<9).

 

<!DOCTYPE HTML>
<html>
<body>
<div>Allowed readers:</div>
<ul>
<li>Bob</li>
<li>Alice</li>
</ul>

<!– a comment node –>

<script>
function go() {
var children = document.body.childNodes

for(var i=0; i<children.length; i++) {
alert(children[i])
}
}
</script>

<button onclick="go()" style="width:100px">Go!</button>

</body>
</html>

 

Sometimes we need to browse only element nodes, skipping text nodes. That’s what the children property is for.

It contains all element nodes. Check out the same example as above, but with children instead ofchildNodes.

It will output only element nodes as it should.

 

 

<!DOCTYPE HTML>
<html>
<body>
<div>Allowed readers:</div>
<ul>
<li>Bob</li>
<li>Alice</li>
</ul>

<!– a comment node –>

<script>
function go() {
var children = document.body.children

for(var i=0; i<children.length; i++) {
alert(children[i])
}
}
</script>

<button onclick="go()" style="width:100px">Go!</button>

</body>
</html>

Comments are closed.