1

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. Setting the innerHTML = ""; removes the contents, using the Jquery .text() or 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.

The text can't be hidden either, it has to be removed

Thanks for any help!

Truvia
  • 370
  • 1
  • 3
  • 14

2 Answers2

2

You could store the DOM elements retrieved with .children, clear the .innerHTML of the div, and re-append the children elements:

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>
LcSalazar
  • 16,524
  • 3
  • 37
  • 69
  • Nice solution! Do you know why pushing the children into the array works and simply using `var children = document.body.children` does not? – spencer.sm Jan 20 '17 at 16:15
  • @spencer.sm `var children = document.body.children` gives you the div not children of the div – user3207158 Aug 22 '17 at 17:13
1

Try this...

elementToRemove = document.getElementById("topDiv").firstChild;
document.getElementById("topDiv").removeChild(elementToRemove);
Dhaval
  • 2,341
  • 1
  • 13
  • 16