tags:

views:

78

answers:

4

Why the function NodeValue__Two() show null? To me, it should show the same thing as the function NodeValue__One().

I have tested this on IE6.

<html>
<body>
<script language="JavaScript">
function NodeValue__One() 
{
   alert(myNodeOne.childNodes(0).nodeValue);//This is OK   
}

function NodeValue__Two() 
{
   alert(document.all[6].nodeValue);//This is NOT OK
}
</script>

<p>This PARAGRAPH has two nodes, 
    <b id="myNodeOne">Node One Text</b>, and 
    <b id="myNodeTwo">Node Two Text</b>.
    <input id="txt1" type="text" value="Damn!!!" /> 
</p>

<button onclick="NodeValue__One();">Node Value 1</button></br>
<button onclick="NodeValue__Two();">Node Value 2</button>

</body>
</html>
+1  A: 

One reason may be that you have erroneously assumed that "This Paragraph has two nodes". It has at least six, including the three text nodes containing "This PARAGRAPH has two nodes,", ", and" and ".".

Paul Butcher
Nope, All doesn't contain text nodes at all.
AnthonyWJones
Good point, I was blinded by the wording to the fact that this was wholly irrelevant.
Paul Butcher
+2  A: 

The All array is an array of Elements. Elements do not have a value in the nodeValue.

On the other hand childNodes will contain both Elements and TextNodes.

Its really hard to get the index of All correct since the number of actual elements listed in All can vary from what you are seeing in the HTML. For example dispite there being no HEAD or TITLE Element present in the HTML text, they will be present in the DOM.

AnthonyWJones
+2  A: 

Both approaches are deprecated and not safe. It would be better if you gave your elements unique identifiers and used getElementById function to find elements in the DOM:

var element = document.getElementById('id_of_element');
Darin Dimitrov
A: 

Use document.all[6].text this will give you Node Two Text

jitter