码迷,mamicode.com
首页 > 其他好文 > 详细

关于nodeValue的困惑

时间:2016-01-29 00:11:24      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

  遍历DOM树节点的nodeValue属性碰到了一个问题。我本意是想取到nodeValue值不为null的节点。

<div id="box">
    <p id="para" class="paragraph">
    这里要写一些文本!!!!!!!!!!!<br>
    这里要写一些文本!!!!!!!!!!!<br>
    这里要写一些文本!!!!!!!!!!!
    </p>
</div>
<script type="text/javascript">
       var box = document.getElementById(‘box‘);
       console.log(box.childNodes);
       var arr = [];
       for(var i = 0; i < box.childNodes.length; i++){
           if(box.childNodes[i].nodeValue != null ){
               arr.push(box.childNodes[i]);
           }
       }
       console.log(arr);        
</script>

Chrome控制台下返回的结果分别是:

[text, p#para.paragraph, text]
[text, text]

元素节点(element node)nodeValue值为null,这个众所周知。属性节点nodeValue值为属性值,文本节点nodeValue值为文本内容。如下,引用自W3C

The values of nodeNamenodeValue, and attributes vary according to the node type as follows:

InterfacenodeNamenodeValueattributes
Attr name of attribute value of attribute null
CDATASection #cdata-section content of the CDATA Section null
Comment #comment content of the comment null
Document #document null null
DocumentFragment #document-fragment null null
DocumentType document type name null null
Element tag name null NamedNodeMap
Entity entity name null null
EntityReference name of entity referenced null null
Notation notation name null null
ProcessingInstruction target entire content excluding the target null
Text #text content of the text node null

那么照说,属性节点符合遍历条件,那么应该被push到attr这个数组中,可是结果属性节点并没有被push进新数组。

关于nodeValue的困惑

标签:

原文地址:http://www.cnblogs.com/coolhector/p/5167640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!