标签:des style color java 使用 io for ar
下面有一段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>
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>
javascript之解决dom中存在的空白节点问题,布布扣,bubuko.com
标签:des style color java 使用 io for ar
原文地址:http://blog.csdn.net/zz410675629/article/details/38556307