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>








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章