I have a function in javascript which should output a text entered into an input field.
My code:
<head>
<script type="text/javascript">
function calculate()
{
var input = document.body.childNodes[1];
document.write(input.value);
}
</script>
</head>
<body>
<input type="text"/>
<input type="button" onclick="calculate()"/>
</body>
Now what I don´t understand is why do I have to put the index “1” into my childNodes array? Logically it should be “0” since <input type="text"/> is the first child of body.
The DOM spec mandates that whitespace betwwen nodes in your HTML, should be presend in the childNodes list, as text nodes. So with HTML like
we would expect the childnodes for the parent div to be
If you want to get only element nodes instead of text nodes, either check the nodeType property of the childnodes when going through the loop (its 1 for elements and 3 for text nodes, IIRC) or use the “children” array instead of “childNodes”.
Note that older browsers might not implement the children array and that Internet Explorer might not show whitespace nodes when iterating through childNodes.