我正在尝试使用javascript从html表中删除某些元素.更具体地说,我需要删除所有不包含两个子字符串的节点.
我试图保存不包含这两个子字符串的节点的位置,然后将其删除.
var posToRemove = [];
var tbody = document.getElementsByTagName("tbody")[0];
var trTags = tbody.getElementsByTagName("tr");
var substring0 = "Foo";
var substring1 = "Bar";
for (i = 0; i < trTags.length; i++) {
var trTextContent = trTags[i].textContent;
if (trTextContent.indexOf(substring0) !== -1 || trTextContent.indexOf(substring1) !== -1) {
//do something
} else {
posToRemove.push(i);
}
}
for (i = 0; i < posToRemove.length; i++) {
trTags[posToRemove[i]].remove();
}
<table>
<tbody>
<tr>
<td><a href="https://example.org">Foo</a></td>
<td>Description</td>
<td>2019</td>
</tr>
<tr>
<td><a href="https://example.org">Test</a></td>
<td>Description</td>
<td>2018</td>
</tr>
<tr>
<td>Bar</td>
<td>Description</td>
<td>2017</td>
</tr>
<tr>
<td><a href="https://example.org">Foo</a></td>
<td>Description</td>
<td>2019</td>
</tr>
<tr>
<td><a href="https://example.org">Test</a></td>
<td>Description</td>
<td>2018</td>
</tr>
<tr>
<td>Bar</td>
<td>Description</td>
<td>2017</td>
</tr>
<tr>
<td>Bar</td>
<td>Description</td>
<td>2017</td>
</tr>
<tr>
<td>Bar</td>
<td>Description</td>
<td>2017</td>
</tr>
<tr>
<td><a href="https://example.org">Foo</a></td>
<td>Description</td>
<td>2019</td>
</tr>
<tr>
<td><a href="https://example.org">Foo</a></td>
<td>Description</td>
<td>2019</td>
</tr>
<tr>
<td><a href="https://example.org">Test</a></td>
<td>Description</td>
<td>2018</td>
</tr>
</tbody>
</table>
可悲的是,它没有按预期工作.它不会仅在表中保留包含这两个字符串之一的元素.我已经检查了保存在数组中的位置,并且都是正确的.
最佳答案
.push()代替i的posToRemove元素,并用trToTags [i] .remove()替换posToRemove [i] .remove().此外,每个字符串的第一个字符都应大写而不是小写,以匹配“ Foo”和“ Bar”.
原文链接:https://www.f2er.com/html/530405.htmlvar posToRemove = [];
var tbody = document.getElementsByTagName("tbody")[0];
var trTags = tbody.getElementsByTagName("tr");
var substring0 = "Foo";
var substring1 = "Bar";
for (let i = 0; i < trTags.length; i++) {
var trTextContent = trTags[i].textContent;
if (trTextContent.indexOf(substring0) !== -1 || trTextContent.indexOf(substring1) !== -1) {
//do something
} else {
posToRemove.push(trTags[i]);
}
}
for (let i = 0; i < posToRemove.length; i++) {
posToRemove[i].remove();
}
<table>
<tbody>
<tr>
<td><a href="https://example.org">Foo</a></td>
<td>Description</td>
<td>2019</td>
</tr>
<tr>
<td><a href="https://example.org">Test</a></td>
<td>Description</td>
<td>2018</td>
</tr>
<tr>
<td>Bar</td>
<td>Description</td>
<td>2017</td>
</tr>
</tbody>
</table>