js的一些困惑

 nodeName,nodeValue

使用时脚本需要写在元素之后,才能正确执行,比如:

<p id = "demo">hello world!</p>

<script>

var value1 = document.getElementById("demo");

document.write(value1.firstChild.nodeValue);

</script>

如果前面就会报错:

Uncaught TypeError: Cannot read property 'firstChild' of null

 

<p id="demo">hello world!</p>
<script type="text/javascript">


var value1 = document.getElementById("demo");

//在上面的例子中,getElementById 是一个方法,而 innerHTML 是属性。
//innerHTML 属性可用于获取或改变任意 HTML 元素,包括 <html> 和 <body>
document.write(value1.nodeValue);
document.write(value1.innerHTML.nodeValue);//注意这个是取不到文本节点
document.write(value1.firstChild.nodeValue);//这个才可以
</script>

posted @ 2016-05-13 11:37  NULL_1  阅读(133)  评论(0编辑  收藏  举报