I'm relatively new to jQuery and am trying to write a function that removes all empty p tags, span tags, strong tags and p and span tags containing only ' '. I've managed to successfully write it but only in a very 'wet' way:
$('p').filter(function() {
return ($(this).html().trim() == ' ');
}).remove();
$('span').filter(function() {
return ($(this).html().trim() == ' ');
}).remove();
$('span').filter(function() {
return ($(this).html().trim() == '');
}).remove();
$('strong').filter(function() {
return ($(this).html().trim() == '');
}).remove();
$('p').filter(function() {
return ($(this).html().trim() == '');
}).remove();
This is the code it plays with:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='test'>
<p>text</p>
<p> </p>
<p>text</p>
<p><span>text</span></p>
<p><span></span></p>
<p>text</p>
<p></p>
<p> </p>
<p>text</p>
<p> </p>
<p><span>text</span></p>
<p></p>
<p><span></span></p>
<p>text</p>
</div>
I've tried to rewrite the code by using a function below, but fails, telling me '$(...).clean is not a function':
function clean() {
return $(this).filter(function() {
return ($(this).html().trim() == ' ');
}).remove();
}
$('p').clean();
$('span').clean();
Other similar posts suggested adding (jQuery);, but this has not worked either.
Can someone explain what I'm doing wrong here, and how to fix it? Or is there an even drier solution for this? I'd rather write fewer lines of code. Also, quick question - when a function is inside another function as above, can 2 return statements be used, or only 1? Thanks for any help here.