No automated tbody with createElement/appendChild?

时光总嘲笑我的痴心妄想 提交于 2019-12-01 10:32:51

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.

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.

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