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($){)


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



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.


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


    Or use filter() method for case insensitive match.

      return $(this).text().toLowerCase().indexOf("target") > -1; 

Related Articles