<p id="p1" align="left" title="title1"></p>
<p id="p2" align="left">蝴蝶飞过<em>是个</em>好地方</p>window.onload=function(){
var p2=document.getElementById("p2");
var p1=document.getElementById("p1");
alert(p1.childNodes.length);
}本人的代码如上,在ie8中测试,p1.childNodes.length为0,p2.childNodes.length为3。
在《DOM编程艺术》中看到说是 childNodes属性包含了属性节点,但测试结果又不是这样。
望老鸟指点迷津
<p id="p2" align="left">蝴蝶飞过<em>是个</em>好地方</p>window.onload=function(){
var p2=document.getElementById("p2");
var p1=document.getElementById("p1");
alert(p1.childNodes.length);
}本人的代码如上,在ie8中测试,p1.childNodes.length为0,p2.childNodes.length为3。
在《DOM编程艺术》中看到说是 childNodes属性包含了属性节点,但测试结果又不是这样。
望老鸟指点迷津
手册上是这么说的:Retrieves a collection of HTML Elements and TextNode objects that are direct descendants of the specified object.
检索对象的直接后代(包括html元素和textNode节点)的集合
<em>是个</em>,一个文本节点"好地方",一共三个节点。如果在其他浏览器中,比如chrome或firefox中那么结果可能就是错误的,它们会把空白文本作为一个文本节点。比如<p id="p3"></p>,这个时候p3.childNodes.length为1,内容是一个空白的文本节点。
<p id="p2" align="left">蝴蝶飞过<em>是个</em>好地方</p>
<p id="p2" align="left">蝴蝶飞过<em>是个</em> </p>
<script>
window.onload=function(){
var p2=document.getElementById("p2");
var p1=document.getElementById("p1");
alert(p1.childNodes.length + "-" + p2.childNodes.length);//有个要注意的地方:这里弹出3-3,因为空格也会被认为是一个子节点。
}
<script>