gpt4 book ai didi

javascript - 如何将 HTMLTableRowElement 插入表体?

转载 作者:行者123 更新时间:2023-11-28 05:47:07 24 4
gpt4 key购买 nike

我查看了table和表体方法,并且没有提及如何插入HTMLTableRowElement。有人知道将 HTMLTableRowElement 插入表体的好方法吗?

const tbody = document.getElementsByTagName('tbody')[0];
// Only inserts an empty row
// Want to insert a HTMLTableRowElement that I've parsed using jsdom
tbody.insertRow();

编辑:在 @frontend_dev 的指导下,它看起来像 jsdom没有使用原生 DOM 元素。因此解决方案可能如下所示:

let rows_rep = '';
jsdom.env(html_with_tr, function(err, w) {
rows_rep = w.document.getElementsByTagName('tr')[0].outerHTML;
}

const tbody = document.getElementsByTagName('tbody')[0];
const newRow = tbody.insertRow();
newRow.innerHTML = rows_rep;

最佳答案

给定一个包含要添加的行的 HTML 字符串,您可以在没有 jsdom 的情况下获取该行并将其附加到当前文档中的表格中:

// Sample HTML string:
var html = `<html>
<body>
<h1>my title</h1>
<table><tr><td>dynamicly added row</td></tr></table>
<p>other text in here</p>
</body>
</html>`;

// Create in-memory element and load HTML into it:
var span = document.createElement('span');
span.innerHTML = html;
// Get the row element out of it, and append it:
var tr = span.querySelector('tr');
var tbody = document.querySelector('tbody');
tbody.appendChild(tr);
<table border=1>
<tr><td>existing row</td></tr>
</table>

关于javascript - 如何将 HTMLTableRowElement 插入表体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com