问题
Creating a table without tbody using javascript createElement/appendChild will not add tbody in Firebug but using innerHTML will do it. Why? Should we add the tbody manually?
回答1:
When using DOM creation methods, it must assume that you want the structure the way you created it.
If you want to ensure the same structure in different browsers, then yes you should always add it manually, even when JavaScript is parsing the HTML. Don't rely on the browser to insert it for you, because browsers may not behave the same in that respect.
Here's an example you can run in Firefox.
It starts off with this invalid markup.
<p>
<div>original</div>
</p>
The <div> gets kicked out of the <p> when the HTML is parsed, leaving it rendered like this...
<p></p>
<div>original</div>
<p></p>
But if we create an identical structure with DOM methods, Firefox doesn't do any corrections.
var p = document.createElement('p');
p.appendChild(document.createElement('div'))
.appendChild(document.createTextNode('new'));
document.body.appendChild(p);
So the resulting DOM is now this...
<p></p>
<div>original</div>
<p></p>
<p>
<div>new</div>
</p>
So you can see that even in the case of a completely invalid structure, it doesn't make the corrections you'd see when it parses HTML.
Ultimately, what you should do is not rely on common browser tweaks or corrections, because there's no guarantee that they will be the same between browsers.
Use well-structured and valid HTML, and you'll avoid problems.
回答2:
Because the start and end tags for the tbody element are optional. You bypass tag insertion by manipulating DOM nodes directly.
Should we add the tbody manually?
That's somewhat subjective.
来源:https://stackoverflow.com/questions/9053572/no-automated-tbody-with-createelement-appendchild