JuanB
JuanB

Reputation: 23

jQuery - if element after another element contains text remove

Suppose this code:

<pre>
  <div class="wp-caption"></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;')" );
    }
});

Upvotes: 1

Views: 47

Answers (3)

JuanB
JuanB

Reputation: 23

In the title I didn't specify the text to be contained is the HTML code "&nbsp" 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

toffler
toffler

Reputation: 1233

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 class="wp-caption"></div>
  <p>&nbsp;</p>
</pre>

<pre>
  <div class="wp-caption"></div>
  <p>&nbsp;</p>
</pre>

<pre>
  <div class="wp-caption"></div>
  <p>test</p>
</pre>

Upvotes: 1

Barmar
Barmar

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

Upvotes: 2

Related Questions