How do you remove text without affecting child elements?

Viewed 451

I have a div with child divs and also some text. Using jQuery/JS I want to leave the child divs alone and remove the text.

<div id="parent">
  <div>keep this</div>
  <div>keep this</div>
  Some random text that can't be predicted (to be removed)
  <div>keep this</div>
</div>
3 Answers

Whit Javascript you can just get all the childNodes of the element with id=parent and then traverse these childs to .remove() those that have nodeType equal to Node.TEXT_NODE:

let childs = document.getElementById("parent").childNodes;
childs.forEach(c => c.nodeType === Node.TEXT_NODE && c.remove());
<div id="parent">
  <div>keep this</div>
  <div>keep this</div>
  Some random text that can't be predicted (to be removed)
  <div>keep this</div>
</div>

Or alternatively and using JQuery.contents() you can use next approach:

$("#parent").contents().each(function()
{
    if (this.nodeType === Node.TEXT_NODE) this.remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="parent">
  <div>keep this</div>
  <div>keep this</div>
  Some random text that can't be predicted (to be removed)
  <div>keep this</div>
</div>

You can use the TreeWalker to find all text nodes which are a direct child of your root element and remove them.

function removeChildTextNodes(root)
{
  var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ALL, {
    acceptNode: function(node) { if(node.nodeType === 3) return NodeFilter.FILTER_ACCEPT },
  }, true);
  var currentNode = treeWalker.firstChild();
  while(currentNode)
  {
      var removedNode = treeWalker.currentNode;
      currentNode = treeWalker.nextNode()
      removedNode.remove();
  }
}

var root = document.querySelector('#parent');
removeChildTextNodes(root);
<div id="parent">
  <img />
  Some random text that can't be predicted (to be removed)
  <div>keep this</div>
  Some random text that can't be predicted (to be removed)
  <h2>
    keep this
  </h2>
  Some <strong>random</strong> text that can't be predicted (to be removed)
  <a>keep this</a>
</div>

Solution using jQuery

$('.parent')
  // Return direct descendants. This also returns text nodes, as opposed to children()
  .contents()
  // Target text nodes only
  .filter(function() {
    return this.nodeType === Node.TEXT_NODE;
  }).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div>keep this</div>
  <div>keep this</div>
  Some random text that can't be predicted (to be removed)
  <div>keep this</div>
</div>

<div class="parent">
  Some random text in another location
  <div>keep this</div>
  <div>keep this</div>
  <div>keep this</div>
  More random text
</div>

Related