How many does the parent node have child node?




<form id="frm1">
<input type="text"/>
<input type="text"/>
</form>
<input type="submit" onclick="myFunction();" value="Göster"/>
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("frm1");

document.write(x.length); // 2 (!) Why?
document.write(x.childNodes.length); // 5 (!) Why?
}
</script>



  1. x.childNodes[0] == first input tag inside form, isn't it?

  2. x.childNodes[1] == second input tag inside form, isn't it?


But the second document.write statement prints number 5. Ok, the two child is above. Well, what is the next three elements? According to w3schools, x.length statement means child number of frm1. But I know from XML lessons in w3schools again that x.length doesn't mean child number of "frm1" or "anything". Namely:



<!DOCTYPE html>
<html>
<body>
<script>
// --------------------- XML DOCUMENT PARSER -------------------------------
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// --------------------------------------------------------------------------


x=xmlDoc.getElementById("first"); // first is an id of XML tag


document.write(x.length + "<br>"); // Output: Undefined
document.write(x.childNodes.length); // Output : 9

</script>
</body>
</html>


Here are xml codes. That is, you can check xml file to understand the code beneath.



<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="first" category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>


If you try run penultimate code snippet in a browser, x.length in penultimate code snippet above outputs "undefined". Does it make sense? I think yes. Then, x.childNodes.length in penultimate code snippet above outputs number 9. That is why there is 4 element nodes and 4 text nodes plus 1 attribute node inside the book element. Total is 9. Why isn't there this situtation in the following?



<form id="frm1">
<input type="text"/>
<input type="text"/>
</form>
<input type="submit" onclick="myFunction();" value="Göster"/>
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("frm1");

document.write(x.length); // 2 ? It must be undefined(!)
document.write(x.childNodes.length); // 5 ? It must be 2(!)
}
</script>


document.write(x.length) involves printing undefined instead of 2, doesn't it? document.write(x.childNodes.length) involves printing number 2 instead of 5, doesn't it?


Could you explain these two question above, please?


No comments:

Post a Comment