我现在已经忙了一段时间,但是我无法解决它。我已经检查了此页面上的所有答案,但仍然无法正常使用。文本保留在页面上。
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 = "";
但是不,没有任何作用,文本仍然在那里...
注:我无法进入源代码来实际更改文本或在文本中添加元素或类名。否则,我就不会打扰。
您能帮忙吗?
您可以通过其前面的元素作为目标,然后获取其nextSibling
:
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>
var container = document.querySelector('.child1');
Array.prototype.forEach.call(container.childNodes, function(node) {
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>
function remove(){
var cNodes = document.querySelector('.child1').childNodes;
cNodes[cNodes.length-1].nodeValue="";
}
¡Hola!
[Hacer esto es muyfácil,con conar el elemento que contiene ambas etiquetas,podríasdevolver el texto:
<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
<button onclick="remove()">Remove the text</button>