How to remove text without removing inner elements from a parent element using JavaScript?

Sometimes, we want to remove text without removing inner elements from a parent element using JavaScript.

In this article, we’ll look at how to remove text without removing inner elements from a parent element using JavaScript.

How to remove text without removing inner elements from a parent element using JavaScript?

To remove text without removing inner elements from a parent element using JavaScript, we can loop through all the child nodes in the element and remove the ones with nodeType 3.

For instance, we write:

<div id='foo'>
  hello world
</div>

to add a div.

Then we write:

const el = document.getElementById("foo")
let child = el.firstChild
let nextChild;

while (child) {
  nextChild = child.nextSibling;
  if (child.nodeType === 3) {
    el.removeChild(child);
  }
  child = nextChild;
}

to select it with getElementById.

Then we loop through the child elements by first getting the first child with firstChild.

And then we use a while loop to get the nextSibling node.

If the nodeType is 3, then we call removeChild to remove it.

As a result, we shouldn’t see ‘hello world’ in the div after the loop is run.

Conclusion

To remove text without removing inner elements from a parent element using JavaScript, we can loop through all the child nodes in the element and remove the ones with nodeType 3.