当找到某个单词时,只将 upmost/nested innertext/innerhtml 设置为 ''

When a certain word is found, only set the upmost/nested innertext/innerhtml to ''

我在当前网页上查找某个词,例如"unique",以删除直接周围标签的内容,但不是更多。

示例

<div>    
  <div>test unique is     
  </div>    
</div>    
<p>Hello     
</p>

变成

<div>    
  <div>   
  </div>    
</div>    
<p>Hello     
</p>

包含标签的 Iow、innerText 或 innerHTML 设置为“”。

到目前为止,我做到了

<script>
var badDivs = $("div:contains('unique')");
badDivs.remove ();
</script>

但我想

  1. 包括所有标签,而不仅仅是 div
  2. 只希望最上面的标签设置为'',而不是整个页面都是空白的,因为嵌套的某个地方有单词unique。
  3. 它应该适用于具有或不具有示例中的属性的标签

看起来好像您不想删除标签,只想删除它的内容因为选择器 *:contains('unique') 选择了每个元素,包括父元素,所以您需要获取最后选择的元素..参见 find, last, and empty

$(function() {
  $(document).find(":contains('unique')").not("script").last().empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>test unique is
  </div>
</div>
<p>Hello
</p>

在这个 Stack Snippet 的例子中,脚本被插入到 iframe 中的 body 元素中,所以我特意排除了这些元素。

过滤包含文本但没有任何其他子元素的元素。

$(':contains("unique")').filter(function(){
  return !$(this).children().length;
}).empty()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>test unique is
  </div>
</div>
<p>Hello
</p>