Selecting the firstChild and whitespace issue

泪湿孤枕 提交于 2019-12-02 12:38:40

问题


I have a markup like this:

<table id='myTable'>
 <thead>
   <tr>
    <td>Hello</td>
   </tr>
 </thead>
</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);

And it returns:

 <TextNode textContent="\n     ">

How should I filter whitespace in getting child nodes?


回答1:


Look at the article here http://www.sitepoint.com/removing-useless-nodes-from-the-dom/

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



回答2:


You can use the .firstElementChild will always return the first element, while the .firstChild might return whitespace (if there is any) to preserve the formatting of the underlying HTML source code.




回答3:


The basic solution is to loop over the children and look of the one with the nodeType you are looking for.

If you don't want to do that yourself, then there are plenty of DOM libraries out there that do it for you (jQuery being the most popular, but not necessarily the best).



来源:https://stackoverflow.com/questions/24907693/selecting-the-firstchild-and-whitespace-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!