Johnny
Johnny

Reputation: 125

JQuery: How To Remove Element By Class If It Doesn't Contain Specified Word?

I'm using JQuery. While doing this works: "$("div.g").remove(":contains('Opportunity')");" When I try doing the opposite: $("div.g:not").remove(":contains('Opportunity')"), it doesn't work. I was curious to know where I went wrong.

Upvotes: 0

Views: 92

Answers (1)

raina77ow
raina77ow

Reputation: 106403

You should apply :not to the selector passed to remove:

$("div.g").remove(':not(:contains("Opportunity"))');

... or use .not() to filter the elements chain-passed to .remove():

$("div.g").not(':contains("Opportunity")').remove();

Here's a snippet showing both approaches in action:

$('button.drop').click(() => {
  $("div.g").remove(':not(:contains("Opportunity"))');
}); 

$('button.drop_by_not').click(() => {
  $("div.g").not(':contains("Opportunity")').remove();
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="g">One</div>
<div class="g">Two</div>
<div class="g">Opportunity</div>
<div class="g">Opportunity Strikes</div>
<div class="g">Three Strikes</div>
<button class="drop">Drop!</button>
<button class="drop_by_not">Drop by Not!</button>

The way you wrote it originally (even if :not has been passed correctly, and not appended to the selector), it'd been applied to div.g elements instead, reverting div.g rule.

Upvotes: 1

Related Questions