如何将 HTMLTableRowElement 插入到 Table 正文中?

How to insert HTMLTableRowElement into a Table Body?

我看过 table 和 table 正文方法,但没有提到如何插入 HTMLTableRowElement。有人知道将 HTMLTableRowElement 插入 table 正文的好方法吗?

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 的情况下获取该行并将其附加到当前文档中的 table:

// 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>