首页 > 代码库 > javascript之解决dom中存在的空白节点问题

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

下面有一段html文档


<body>
    <h1>Introduction to the DOM</h1>
    <p class="test">There are a number of reasons why the DOM is awesome, here are some:</p>
    <ul>
        <li id="everywhere">It can be found everywhere.</li>
        <li class="test">It's easy to use.</li>
        <li class="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)
        console.info(a.childNodes[0].nodeType);
        //清除空白函数
        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)
                }
            }
        }

    };

    
    </script>
</head>
<body>
    <h1>Introduction to the DOM</h1>
    <p class="test">There are a number of reasons why the DOM is awesome, here are some:</p>
    <ul>
        <li id="everywhere">It can be found everywhere.</li>
        <li class="test">It's easy to use.</li>
        <li class="test">It can help you to find what you want, really quickly.</li>
    </ul>
</body>
</html>