No automated tbody with createElement/appendChild?

我与影子孤独终老i 提交于 2019-12-30 11:29:06

问题


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

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