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?
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>
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With