求助:使用insertBefore将HTML表格插入指定子div内的正确位置
解决办法
你当前的代码是把表格插入到父容器的子元素之间,而非目标子div的内部。要实现需求,得先定位到那个标注的子div,再将表格添加到它内部。
修改后的代码方案
方案1:把表格追加到目标div末尾
// 创建标准HTML表格 const table = createTable({ data, propertyId }); let wrapper = document.querySelector(classes.propertySummary); // 获取标注的目标子div(wrapper的第一个子元素) const targetDiv = wrapper.children[0]; // 将表格添加到目标div内部的末尾 targetDiv.appendChild(table);
方案2:把表格插入到目标div内容的最前面
如果需要表格放在目标div内的第一个位置,用insertBefore:
// 创建标准HTML表格 const table = createTable({ data, propertyId }); let wrapper = document.querySelector(classes.propertySummary); const targetDiv = wrapper.children[0]; // 插入到目标div的第一个子元素之前(div为空时会直接添加) targetDiv.insertBefore(table, targetDiv.firstChild);
修改后对应的DOM结构
如果用方案1,结构会是这样(表格在文本之后):
<div class="summary"> <div> Where my table should sit inside <table></table> </div> <div></div> </div>
如果用方案2,结构会是这样(表格在文本之前):
<div class="summary"> <div> <table></table> Where my table should sit inside </div> <div></div> </div>
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

