3 回答
TA贡献1834条经验 获得超8个赞
您可以轻松过滤直接子节点中的文本节点:
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>
TA贡献1817条经验 获得超14个赞
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
TA贡献1788条经验 获得超4个赞
您可以通过它前面的元素来定位它,然后获取它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>
- 3 回答
- 0 关注
- 124 浏览
添加回答
举报