Jquery – Remove only text content from a div

This should do the trick:

$('#YourDivId').contents().filter(function(){
    return this.nodeType === 3;
}).remove();

Or using an ES6 arrow function:

$('#YourDivId').contents().filter((_, el) => el.nodeType === 3).remove();

If you want to make your code more readable and you only need to support IE9+, you can use the node type constants. Personally, I’d also split the filter function out and name it, for reuse and even better readability:

let isTextNode = (_, el) => el.nodeType === Node.TEXT_NODE;

$('#YourDivId').contents().filter(isTextNode).remove();

Here’s a snippet with all the examples:

$('#container1').contents().filter(function() {
  return this.nodeType === Node.TEXT_NODE;
}).remove();

$('#container2').contents().filter((_, el) => el.nodeType === Node.TEXT_NODE).remove();

let isTextNode = (_, el) => el.nodeType === Node.TEXT_NODE;

$('#container3').contents().filter(isTextNode).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container1">
  <h1>This shouldn't be removed.</h1>
  This text should be removed.
  <p>This shouldn't be removed either.</p>
  This text should also be removed.
</div>

<div id="container2">
  <h1>This shouldn't be removed.</h1>
  This text should be removed.
  <p>This shouldn't be removed either.</p>
  This text should also be removed.
</div>

<div id="container3">
  <h1>This shouldn't be removed.</h1>
  This text should be removed.
  <p>This shouldn't be removed either.</p>
  This text should also be removed.
</div>

Leave a Comment