我正在尝试以编程方式转换表格以删除一些我不想要的标签。我编写了一个递归函数,该函数在表元素上调用,并在所有子元素上调用自身,创建这些子元素的列表,并用这些已清理的子元素替换当前的子元素。但是,节点未正确添加,而是 [object HTMLTableSectionElement] 或 [object Text] 的字符串表示形式最终出现在输出中。
(对于那些对上下文感兴趣的人:我使用 thead、tbody 和几个自定义标签来创建一个精美的表格,但我也希望能够按一个按钮将表格复制到不支持这些标签的维基百科页面中,所以在复制到剪贴板时我必须删除它们,否则看起来很糟糕)
这是我的职责:
function prepHTMLforExport(element){
//recursively goes into an HTML element, preparing it for export by:
//removing thead and tbody statements but leaving their contents in the parent element
//removing floattext tags
//replacing hyperlink a tags with ...
//go through child elements and prep each for export
var newchildren = []
var children = element.childNodes
for (var i=0;i<children.length;i++){
var newkid = prepHTMLforExport(children[i])
//if the new kid is actually a list, concat the lists
if (newkid instanceof Array){
newchildren.concat(newkid)
} else {
newchildren.push(newkid)
}
}
//if to be removed, return a list of children
if (element.tagName in ["floattext", "table-body", "table-head"]){
return newchildren
} else {
//else add children to self and return self
if (newchildren.length > 0) {
element.replaceChildren(newchildren)
}
return element
}
}
它基本上应该适用于任何 HTML 表格。
我最初怀疑我检查了错误的子项或使用了错误的方法来替换它们,所以我也尝试了
var children = element.children
,并且我查看是否有不同的函数用于替换,例如replaceWith,但仔细检查我发现这没有帮助。元素在处理时已经在其父节点列表中转换为错误的形式,而不仅仅是在我将它们替换为经过净化的版本之后。为了测试这一点,有这张表:
<table>
<th>sample text</th>
<th>some more sample text</th>
</table>
单步执行代码时,如果代码刚刚准备好第一个单元格,并且现在要递归到第二个单元格,如果执行
console.log(element)
,则会导致
<table>
<th>[object Text]</th>
<th>some more sample text</th>
</table>
您的问题是
.element.replaceChildren
希望每个子项都是一个单独的参数,但是您传递的是一个数组。
因此
.replaceChildren
将数组转换为字符串,给出
[object Text],[object HTMLTableSectionElement]
中间额外的
,
逗号是一个额外的提示,表明这是一个转换为字符串的数组
您可以使用rest参数将数组转换为参数 - 您的代码行将变为:
element.replaceChildren(...newchildren)
更新片段:
function prepHTMLforExport(element) {
//recursively goes into an HTML element, preparing it for export by:
//removing thead and tbody statements but leaving their contents in the parent element
//removing floattext tags
//replacing hyperlink a tags with ...
//go through child elements and prep each for export
var newchildren = []
var children = element.childNodes
for (let i = 0; i < children.length; i++) {
var newkid = prepHTMLforExport(children[i])
//if the new kid is actually a list, concat the lists
if (newkid instanceof Array) {
newchildren = newchildren.concat(newkid);
} else {
newchildren.push(newkid)
}
}
//if to be removed, return a list of children
if (element.tagName in ["floattext", "table-body", "table-head"]) {
return newchildren
} else {
//else add children to self and return self
if (newchildren.length > 0) {
element.replaceChildren(...newchildren);
}
return element
}
}
prepHTMLforExport(document.getElementById("tbl"));
<table id='tbl'>
<th>sample text</th>
<th>some more sample text</th>
</table>