Reputation: 370
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!
Upvotes: 1
Views: 2329
Reputation: 16831
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>
Upvotes: 2
Reputation: 2379
Try this...
elementToRemove = document.getElementById("topDiv").firstChild;
document.getElementById("topDiv").removeChild(elementToRemove);
Upvotes: 1