[英]jQuery remove element that contains another element with the class of ___
[英]How to remove element by class only if it contains an element with some specified text?
<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" 的元素?
您可以使用函数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>
您可以使用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.
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.