简体   繁体   中英

JavaScript - DOM nodeValue problem

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>

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.

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');

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 ".".

使用document.all[6].text这将为您提供Node Two Text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM