天天看點

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    如需轉載請自行聯系原作者

繼續閱讀