假设我的代码中有这个结构:
<div>
<div>This is my text</div>
<div>Text continues...</div>
</div>
<div>
<div>Another text</div>
<div>Other text</div>
</div>
<div>
<div>This is my text</div>
<div>Text continues...</div>
</div>
我想要做的是(没有jquery):
搜索这是我的(意识到我没有通过全文.只是其中的一部分,这是我的).
每当我找到包含这部分文本的div时,我想删除父div!因此,删除其中的所有内容,包括:
<div>This is my text</div>
and
<div>Other text</div>
因此,我只会这样:
<div>
<div>Another text</div>
<div>Other text</div>
</div>
我试过这种方式:
var elems = document.querySelectorAll("div"),
res = Array.from(elems).find(v => v.textContent == 'Vídeos que contêm');
alert(res ? 'found!' : 'not found');
但它会搜索特定的文字!
它仍然不适用于每一次事件.
最佳答案 您的代码不起作用,因为:
>您试图检查textContent是否等于(==)字符串,但您需要检查文本内容是否为includes
字符串.
>它只是找到元素而不会删除它们.您需要使用.remove()
删除元素.
document.querySelectorAll("div > div:first-child").forEach(ele => {
ele.textContent.includes('This is my') && ele.parentNode.remove();
});
document.querySelectorAll("div > div:first-child").forEach(ele => {
ele.textContent.includes('This is my') && ele.parentNode.remove();
});
<div>
<div>This is my text</div>
<div>Text continues...</div>
</div>
<div>
<div>Another text</div>
<div>Other text</div>
</div>
<div>
<div>This is my text</div>
<div>Text continues...</div>
</div>
I’m trying to do with no jquery
虽然你不想使用jQuery,但它很简单,代码也少
$("div > div:contains('This is my')").parent().remove();
$("div > div:contains('This is my')").parent().remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>This is my text</div>
<div>Text continues...</div>
</div>
<div>
<div>Another text</div>
<div>Other text</div>
</div>
<div>
<div>This is my text</div>
<div>Text continues...</div>
</div>