Suppose this code:
<pre>
<div ></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(' ')" );
}
});
CodePudding user response:
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();
});
CodePudding user response:
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 ></div>
<p> </p>
</pre>
<pre>
<div ></div>
<p> </p>
</pre>
<pre>
<div ></div>
<p>test</p>
</pre>