Selecting the firstChild and whitespace issue

2020-04-21 06:34发布

问题:

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:

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.



回答2:

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


回答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).