选择firstChild和whitespace问题 [英] Selecting the firstChild and whitespace issue

查看:115
本文介绍了选择firstChild和whitespace问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的标记:

<table id='myTable'>
 <thead>
   <tr>
    <td>Hello</td>
   </tr>
 </thead>
</table>

但是当我尝试选择的第一个孩子时#table ,它返回空格(正如预期的那样)。

But when I try to select the firstChild of #table, it returns whitespace (as it is expected).

var ss = document.getElementById("myTable");
console.log(ss.firstChild);

它返回:

 <TextNode textContent="\n     ">

如何在获取子节点时过滤空格?

How should I filter whitespace in getting child nodes?

推荐答案

请看这里的文章 http://www.sitepoint.com/removing-useless-nodes-from-the-dom/

这家伙给了一个JS过滤掉所有空白子节点的函数。

This guy has given a JS function that filters out all the whitespace childnodes.

您可以在该文章中详细了解该功能的工作原理以及它为何如此方便。我将在这里复制粘贴代码。

You can read the details of how the function works and why it can be so handy in that article. I will just copy-paste the code here.

function clean(node)
{
   for(var n = 0; n &lt; node.childNodes.length; n++)
   {
       var child = node.childNodes[n];
       if (child.nodeType === 8 || (child.nodeType === 3 && !/S/.test(child.nodeValue)))
       {
          node.removeChild(child);
          n--;
       }
       else if(child.nodeType === 1)
       {
          clean(child);
       }
   }
}

这篇关于选择firstChild和whitespace问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆