天天看点

javascript之解决DOM中存在的空白节点问题

<body>

    <h1>Introduction to the DOM</h1>

    <pclass="test">There are a number of reasons why the DOM is awesome, here are some:</p>

    <ul>

        <liid="everywhere">It can be found everywhere.</li>

        <liclass="test">It's easy to use.</li>

        <liclass="test">It can help you to find what you want, really quickly.</li>

    </ul>

</body>

当我们得到ul标签的下一个节点的时候,我们会习惯的引用下面的js

var every = document.getElementById( "everywhere" );  

       // and remove it from the document

console.info(every.parentNode.childNodes[0].nodeType);  

但是我们发现,控制台打印的nodeType:3.(chorme浏览器测试)

出现这样的问题是因为什么呢?

这是因为在UL标签和LI标签之间出现了空格,被浏览器误认为是文本节点,所以打印出nodeType=3,而实际我们需要得到的是元素节点LI

如何解决这个问题呢?

原理很简单,即去除节点之间的空格即可;

下面就是一段清除空格的函数

function cleanWhitespace(oEelement){  

            for(var i=0;i<oEelement.childNodes.length;i++){  

                var node=oEelement.childNodes[i];  

                if(node.nodeType==3 && !/\S/.test(node.nodeValue)){  

                    node.parentNode.removeChild(node)  

                }  

            }  

        }  

通过使用此函数,控制台打印出来的nodeType:1--》这才是正解。

具体详细例子见如下index.html

<html>

<head>

    <title>Introduction to the DOM</title>

    <script>

    // We can't manipulate the DOM until the document  

    // is fully loaded  

    window.onload = function(){  

        // Locate the element with an ID of 'everywhere'  

        var every = document.getElementById( "everywhere" );  

        // and remove it from the document  

        var a=every.parentNode;  

        console.info(a.childNodes[0].nodeType);  

        cleanWhitespace(a)  

        //清除空白函数  

        function cleanWhitespace(oEelement){  

    };  

    </script>

</head>

</html>

--------------------------------------------------------------------------

//忽略空白字符

function filterWhiteNode(node) {

var ret = [];

for (var i = 0; i < node.length; i ++) {

if (node[i].nodeType === 3 && /^\s+$/.test(node[i].nodeValue)) {

continue;

} else {

ret.push(node[i]);

}

return ret;

//移除空白字符

function removeWhiteNode(node) {

node[i].parentNode.removeChild(node[i]);

return node;

*/

window.onload = function () {

var box = document.getElementById('box');

alert(removeWhiteNode(box).firstChild.nodeName);

};

//移除空白节点

for (var i = 0; i < node.childNodes.length; i ++) {

if (node.childNodes[i].nodeType === 3 && /^\s+$/.test(node.childNodes[i].nodeValue)) {

node.childNodes[i].parentNode.removeChild(node.childNodes[i]);

}本文转自    风雨萧条 博客,原文链接:    http://blog.51cto.com/1095221645/1877906    如需转载请自行联系原作者

继续阅读