为何调用createTHead后,table.insertRow()添加的<tr>进入<thead>而非<tbody>
table.insertRow() 插入行进入thead而非tbody的原因及解决方法
原因
当调用table.insertRow()且未传入参数时,DOM API的默认逻辑是将新行插入到表格的最后一个已存在的表格节(thead/tfoot/tbody)中。
你的代码先通过table.createTHead()创建了thead元素,此时表格内仅存在thead这一个表格节,浏览器不会自动生成tbody(只有当表格存在行但无thead/tfoot时,才会自动创建tbody)。因此调用table.insertRow()时,新行被追加到了唯一的thead里。
解决方法
方法一:手动创建tbody并通过其插入行
const table = document.createElement("TABLE"); const thead = table.createTHead(); const tr = thead.insertRow(); const th1 = tr.insertCell(); th1.textContent = "header1"; const th2 = tr.insertCell(); th2.textContent = "header2"; // 手动创建tbody并插入行 const tbody = table.createTBody(); const tr2 = tbody.insertRow(); const td1= tr2.insertCell(); td1.textContent = "field1"; const td2 = tr2.insertCell(); td2.textContent = "field2"; document.getElementById("main").appendChild(table);
方法二:先获取或创建tbody,再插入行
const table = document.createElement("TABLE"); const thead = table.createTHead(); const tr = thead.insertRow(); const th1 = tr.insertCell(); th1.textContent = "header1"; const th2 = tr.insertCell(); th2.textContent = "header2"; // 获取现有tbody,不存在则创建 let tbody = table.querySelector('tbody'); if (!tbody) { tbody = table.appendChild(document.createElement('tbody')); } const tr2 = tbody.insertRow(); const td1= tr2.insertCell(); td1.textContent = "field1"; const td2 = tr2.insertCell(); td2.textContent = "field2"; document.getElementById("main").appendChild(table);
内容的提问来源于stack exchange,提问作者Benjamin
相关产品推荐
相关产品推荐

