Home > Mobile >  jQuery - if element after another element contains text remove
jQuery - if element after another element contains text remove

Time:07-21

Suppose this code:

<pre>
  <div ></div>
  <p>&nbsp;</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('&nbsp;')" ) ) {
        $( "p" ).remove( ":contains('&nbsp;')" );
    }
});

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('&nbsp;')").remove();
});

CodePudding user response:

Following the answer of Barmar, this can even be accomplished by a one liner:

$('div.wp-caption').next("p:contains('&nbsp;')").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('&nbsp;')").remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
  <div ></div>
  <p>&nbsp;</p>
</pre>

<pre>
  <div ></div>
  <p>&nbsp;</p>
</pre>

<pre>
  <div ></div>
  <p>test</p>
</pre>

  • Related