我正在通过我的代码在需要的地方用 JS 替换 jQuery,在某些情况下我需要清除和重建一些表数据,为此我按以下方式使用 jQuery:
$("[id*='mg_row_document'] td:nth-of-type(2)").html('');
我能够为纯 JS 组合起来的就是这个,但是不起作用,我只获得元素的 NodeList,然后必须循环通过 el 来执行 getElementsByTagName。有没有办法像 jQuery 一样一次性改变它们?
el = document.querySelectorAll('[id^="mg_row_document"]');
el.getElementsByTagName('td')[2].innerHTML = '';
最佳答案
如果您的 jQuery 选择器以前适合您,则可以通过 querySelectorAll()
重用它,但请记住,它不是一个随时可用的 jQuery 集合。相反,您将拥有一个需要使用循环进行迭代的 NodeList。详细信息在代码片段中评论。
片段
/* target is a NodeList. A NodeList is an
| array-like object, but not a real array.
| The first half of this selector is most
| likely not needed. If given the real HTML
| we'd know for sure.
*/
var target = document.querySelectorAll("[id*='mg_row_document'] td:nth-of-type(2)");
// Determine the number of tds in NodeList
var qty = target.length;
/* This for loop is saying:
| "`i` starts at 0 (i=0)...
| ...For each iteration (for)...
| ...while `i` is less than (i < )...
| ...the total amount of `td`s (qty)...
| ...`i` will increase by 1 (i++)...
*/
for (let i = 0; i < qty; i++) {
/* Using bracket notation to specify
| the index position of each `td`.
| Each iteration, the `style` property
| is used to change each `td` background
| color to yellow.
*/
target[i].style.backgroundColor = 'yellow';
}
table,
td {
border: 1px solid black;
}
<table id='mg1_documentA'>
<tr id='mg_row_documentA1'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentA2'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentA3'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentA4'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
</table>
<table id='mg1_documentB'>
<tr id='mg_row_documentB1'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentB2'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentB3'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentB4'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
</table>
<table id='mg1_documentC'>
<tr id='mg_row_documentC1'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentC2'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentC3'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr id='mg_row_documentC4'>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
</table>
关于javascript - 更改多个子元素的 HTML(这个 jquery 选择器的 JS 版本是什么?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41151383/