gpt4 book ai didi

javascript - 更改多个子元素的 HTML(这个 jquery 选择器的 JS 版本是什么?)

转载 作者:行者123 更新时间:2023-11-29 17:53:39 26 4
gpt4 key购买 nike

我正在通过我的代码在需要的地方用 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/

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