Reputation: 23
Suppose this code:
<pre>
<div class="wp-caption"></div>
<p> </p>
</pre>
I would like to check if after a <div>
with class wp-caption
there is a <p>
with nbsp;
. If there is, remove it.
My attempt:
jQuery(document).ready(function($) {
if ( $( 'div.wp-caption' ).next().is( "p:contains(' ')" ) ) {
$( "p" ).remove( ":contains(' ')" );
}
});
Upvotes: 1
Views: 47
Reputation: 23
In the title I didn't specify the text to be contained is the HTML code " " which couldn't be selected straightforward but had to be replaced with "\u00a0" Both answers where right, just that details. Thanks!
$('div.wp-caption').next("p:contains(\u00a0)").remove();
Upvotes: 1
Reputation: 1233
Following the answer of Barmar, this can even be accomplished by a one liner:
$('div.wp-caption').next("p:contains(' ')").remove();
There is not really a need to loop before, because the selector applies on every element by default.
$('div.wp-caption').next("p:contains(' ')").remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
<div class="wp-caption"></div>
<p> </p>
</pre>
<pre>
<div class="wp-caption"></div>
<p> </p>
</pre>
<pre>
<div class="wp-caption"></div>
<p>test</p>
</pre>
Upvotes: 1
Reputation: 781058
Use .each()
to loop over all the div.wp-caption
elements, and remove the next element if it matches the :contains()
criteria.
$('div.wp-caption').each(function() {
$(this).next("p:contains(' ')").remove();
});
Upvotes: 2