jQuery if element:contains Isn't Working

This question already has an answer here:

I have a site with code reminiscent to this code and I don't understand why the if statement isn't working. From looking at other code examples, my guess is that I need another function above my if statement? (instead of the jQuery(document).ready(function($){)

HTML:

<p>Paragraph One</p>
<p class="red">Target paragraph</p>

jQuery:

jQuery(document).ready(function($){
  if($('p:contains("target")')){
    $(this).removeClass("red");
  }
)};

jsFiddle: https://jsfiddle.net/CSS_Apprentice/2a2qpg15/

Worth Noting: Using jQuery(document).ready(function($){ because it's a WordPress build.

edit: Leaving the lowercase version of "target" in here, but case sensitivity wasn't the only issue

Any help, direction, and/or docs appreciated!

Answers 1

  • Check length property since jQuery returns an object which is always truthy value in JavaScript. Although :contains is case sensitive so use Target instead.

    if($('p:contains("Target")').length)
    

    For removing apply remove() method directly on the $('p:contains("Target")') since this is not refers to the element.

    $('p:contains("Target")').remove();
    

    Or use filter() method for case insensitive match.

    $('p').filter(function(){ 
      return $(this).text().toLowerCase().indexOf("target") > -1; 
    }).remove()
    

Related Articles