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>








  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值