<tr class="Action Head" data-index="1">
<td class="Template">
<div class="Description">
<span class="Text Description" id="MainDescription">text</span>
</div>
</td>
</tr>
如果带有id =“MainDescription”的span包含一些指定的文本,如何使用class =“Action Head”删除元素?
您可以使用Array.filter
按内容选择元素,使用检查元素内容的函数来查看它是否符合您的要求。例如:
//variable rowsToRemove will be an array that contains all the rows that contain
//a span with id MainDescription which contain the word 'text'
var rowsToRemove = [].filter.call(document.querySelectorAll('.Action.Head'), function(row){
var mainDescriptionSpan = row.querySelector('span#MainDescription');
return (mainDescriptionSpan && mainDescriptionSpan.textContent.indexOf('text') != -1);
});
if (rowsToRemove.length) { //if there are some row(s) that match the criteria...
rowsToRemove.forEach(function(row){ // ... loop through all of them ...
row.remove(); // ... and remove them.
});
}
您可以使用函数querySelectorAll
来收集整个元素集Action Head
然后循环遍历这些元素,并为每个Action Head
元素获取其span元素。
使用span
元素检查属性textContent
。
此代码段只会删除一个TR。
var actions = document.querySelectorAll('.Action.Head');
Array.prototype.forEach.call(actions, function(action) {
var span = action.querySelector('span');
if (span.textContent === 'text') span.remove();
});
<table>
<tbody>
<tr class="Action Head" data-index="1">
<td class="Template">
<div class="Description">
<span class="Text Description" id="MainDescription">text</span>
</div>
</td>
</tr>
<tr class="Action Head" data-index="1">
<td class="Template">
<div class="Description">
<span class="Text Description" id="MainDescription2">text2</span>
</div>
</td>
</tr>
</tbody>
</table>