选择firstChild和空白问题

Selecting the firstChild and whitespace issue

本文关键字:问题 空白 firstChild 选择      更新时间:2023-09-26

我有一个这样的标记:

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

但是当我尝试选择#table的firstChild时,它返回空白(正如预期的那样)。

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

返回:

 <TextNode textContent="'n     ">

我应该如何过滤空格在获得子节点?

您可以使用. firstelementchild将始终返回第一个元素,而. firstchild可能返回空白(如果有的话)以保留底层HTML源代码的格式。

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

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

您可以在那篇文章中阅读该函数如何工作的细节以及为什么它如此方便。我把代码复制粘贴到这里。

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);
       }
   }
}

基本的解决方案是循环遍历子节点并查找具有您正在寻找的nodeType的子节点。

如果你不想自己做,那么有很多DOM库可以帮你做(jQuery是最流行的,但不一定是最好的)。