是否可以替换HTML表格第一行的所有内容而不为每个元素分配ID< td>?

thtygnil  于 2023-06-04  发布在  其他
关注(0)|答案(3)|浏览(99)

我有一个简单的HTML表格,由表格标题和第一行组成,如下所示:

<html>
<table>
<thead>
<th>name</th>
<th>email</th>
</head>
<tr>
<td>Kipchoge</td>
<td>k@gmail.com</td>
</tr>
</table>

<input type="button" id="btn" value="btn" onClick="fn()"/>
</html>

单击按钮时,如何使用自定义文本更改第一行的所有内容?我尝试将我的新文本直接分配给document.getElementByTagName("tr")[1].innerHTML,但没有成功,如下面的代码所示:

function fn(){
var d = document.getElementsByTagName('tr');
var customtext = "";
d[1].innerHTML = customtext;
}
<table>
<thead>
<th>name</th>
<th>email</th>
</head>
<tr>
<td>Kipchoge</td>
<td>k@gmail.com</td>
</tr>
</table>
<input type="button" id="btn" value="btn" onClick="fn()"/>

我知道我在上面的代码中所做的是尝试为现有的innerHTML值分配一个新值,这在使用getElementById时很容易实现,但我的想法是一次性更改第一行的所有值,而不为每个<td></td>分配id。是否有替代方法?或者我应该如何处理我的方法来解决这样的问题?
我尝试用新文本更改现有的innerHTML,如下所示:

d[1].innerHTML = customtext;

但这并不奏效。

83qze16e

83qze16e1#

函数getElementsByTagName返回一个live HTMLCollection,它是一个类似数组的元素对象。在您的代码中,您试图在表行节点中添加文本。表行-或tr-只允许在其中包含td元素。在下面的示例中,我使用innerHTML来设置表示的HTML,该HTML包含td,其中包含文本。

function fn(){
  var tr = document.getElementsByTagName('tr')[0];
  tr.innerHTML = `<td>Text 1</td><td>Text 2</td>`;
}
<table>
  <thead>
    <th>name</th>
    <th>email</th>
  </thead>
  <tr>
    <td>Kipchoge</td>
    <td>k@gmail.com</td>
  </tr>
</table>

<input type="button" id="btn" value="btn" onClick="fn()"/>
</html>
ibrsph3r

ibrsph3r2#

使用更强大的querySelector方法通过CSS选择器从DOM中选择元素。在这种情况下,您可以使用tbody tr:first-of-type选择第一行。

const firstTableRow = document.querySelector('tbody tr:first-of-type');

firstTableRow.cells[0].textContent = 'Foo';
firstTableRow.cells[1].textContent = 'foo@bar.com';
<table>
  <thead>
    <th>name</th>
    <th>email</th>
  </thead>

  <tbody>
    <tr>
      <td>Kipchoge</td>
      <td>k@gmail.com</td>
    </tr>
    
    <tr>
      <td>Kipchoge</td>
      <td>k@gmail.com</td>
    </tr>
  </tbody>
</table>
ua4mk5z4

ua4mk5z43#

您可以通过这种方式遍历表头

<html>
<table>
<thead>
<th>name</th>
<th>email</th>
</head>
<tr>
<td>Kipchoge</td>
<td>k@gmail.com</td>
</tr>
</table>

<input type="button" id="btn" value="btn" onClick="fn()"/>
</html>

// you can target thead and get all ths that are present inside it

const head = document.getElementById("thead-id") /* or */ document.querySelector('thead')
// if you don't want all th in thead only the ones in first row of the thead
//(incase you have more than one rows in thead)
const row = document.querySelector("thead tr:first-of-type") /* or */ document.querySelector("#thead-id tr:first-of-type")

const thList = head.querySelectorAll("th");
// or 
const thList = row.querySelectorAll("th");
// Now th list acts like a list or an array where you can target items using index or run a forEach loop
thList.forEach((th) => {
th.innerText = "customText"
})

相关问题