简体   繁体   English

只删除div中的文本,但不删除子元素 - NOT JQUERY

[英]Remove text in div ONLY but not in child elements - NOT JQUERY

So I have the following setup: 所以我有以下设置:

    <div class='topDiv'>
      SomeText
       <span>ChildText</span>
      OtherText
       <span>ChildText</span>
      DifferentText
    </div>

How do I remove the text "sometext", "othertext" and "DifferentText" in javascript (not Jquery) without removing the child text. 如何在不删除子文本的情况下在javascript(而不是Jquery)中删除文本“sometext”,“othertext”和“DifferentText”。 Setting the innerHTML = ""; 设置innerHTML =“”; removes the contents, using the Jquery .text() or JavaScript .textContent = ""; 使用Jquery .text()或JavaScript .textContent =“”删除内容; doesn't work either. 也不起作用。

I had a look at the first answer below, but this would only return the first SomeText (what I'm really looking for is something that would remove or select all the text xin the topDiv without affecting the spans. 我看了下面的第一个答案,但这只会返回第一个SomeText(我真正想要的是删除或选择topDiv中的所有文本而不影响跨度的东西。

The text can't be hidden either, it has to be removed 文本也无法隐藏,必须将其删除

Thanks for any help! 谢谢你的帮助!

You could store the DOM elements retrieved with .children , clear the .innerHTML of the div, and re-append the children elements: 您可以存储使用.children检索的DOM元素,清除div的.innerHTML ,并重新附加子元素:

 var div = document.querySelector(".topDiv"); var children = []; for(var i=0; i<div.children.length; i++) { children.push(div.children[i]); } div.innerHTML = ""; children.forEach(function(item) { div.appendChild(item); }); 
 <div class='topDiv'> SomeText <span>ChildText</span> <span>ChildText</span> </div> 

Try this... 尝试这个...

elementToRemove = document.getElementById("topDiv").firstChild;
document.getElementById("topDiv").removeChild(elementToRemove);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM