我现在已经忙了一段时间,但是我无法解决它。我已经检查了此页面上的所有答案,但仍然无法正常使用。文本保留在页面上。
Using .text() to retrieve only text not nested in child tags
我的HTML:
<div class="parent">
<div class="child1">
<div class="child-of-child1">
A lot of elements here
</div> -----> (closing child of child 1)
TEXT I LIKE TO REMOVE
</div> -----> (closing child 1)
</div>
我尝试过的是该主题中的所有内容。仅供参考,我也尝试过以下方法:
document.getElementsByClassName('child-of-child1').childNodes[0].nodeValue = "";
但是不,没有任何作用,文本仍然保留在其中...
注意:我无法进入源代码来实际更改文本或在文本中添加元素或类名。否则,我就不会打扰。
可以帮忙吗?
答案 0 :(得分:2)
您可以通过其前面的元素作为目标,然后获取其nextSibling
:
const textNode = document.querySelector(".parent .child1 .child-of-child1").nextSibling;
textNode.parentNode.removeChild(textNode);
实时示例:
setTimeout(() => {
const textNode = document.querySelector(".parent .child1 .child-of-child1").nextSibling;
textNode.parentNode.removeChild(textNode);
}, 800);
<div class="parent">
<div class="child1">
<div class="child-of-child1">
A lot of elements here
</div>
TEXT I LIKE TO REMOVE
</div>
</div>
答案 1 :(得分:2)
您可以轻松过滤直接子级中的文本节点:
var container = document.querySelector('.child1');
for(var node of container.childNodes) {
if (node.nodeType === Node.TEXT_NODE) {
container.removeChild(node);
}
}
<div class="parent">
<div class="child1">
THIS WILL DISAPPEAR
THIS WILL DISAPPEAR
<div class="child-of-child1">
A lot of elements here
</div>
THIS WILL DISAPPEAR
</div>
</div>
答案 2 :(得分:1)
var cNodes = document.querySelector('.child1').childNodes;
if(cNodes.length>0)
cNodes[cNodes.length-1].nodeValue="";
<div class="parent">
<div class="child1">
<div class="child-of-child1">
A lot of elements here
</div>
TEXT I LIKE TO REMOVE
</div>
</div>
Hello