Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Remove only text content from a div

Tags:

jquery

is possible to remove only text content from a div, i.e. leave all other elements intact and only remove text that is directly inside a div?

like image 906
David Avatar asked Aug 06 '10 08:08

David


2 Answers

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>
like image 159
Mark Bell Avatar answered Nov 09 '22 11:11

Mark Bell


Assuming the following HTML structure:

<div class="element-to-clean">
  Content to be filtered out.
  <span class="element-to-leave-intact">
    Content to be left inthe element.
  </span>
</div>

You can achieve your desired behavior by using the following JavaScript + jQuery 2.1 code:

$('.element-to-clean').html($('.element-to-clean').children());
like image 38
Artur Black Avatar answered Nov 09 '22 11:11

Artur Black