jQuery :contains() — Selecting Elements Based On Content

jquery containsThe jQuery :contains() selector allows you to select elements that contain a specified string; once you have selected the elements, you can do something with them, of course, such as displaying them.  This ability to select elements, then take action makes the :contains() selector a valuable tool for displaying dynamic web content.

Want to know more about jQuery and JavaScript?  There are plenty of good online courses, from beginning to advanced, in these subjects and more.  Check some out today!

jQuery:  A Little Background

Before we dive in, here’s a quick look at what jQuery is all about:

jQuery is an open-source JavaScript library; its main purpose is to make it easier to work with web pages and HTML, and to handle scripting for many dynamic web page functions, particularly at the client end. It can be used with AJAX and Microsoft Visual Studio, and can be included in a web page either as a local copy (it is a single, downloadable JavaScript file), or from one of the publicly-available hosted locations.  You use the $ prefix to access jQuery commands, typically followed by a selection command or statement, called a “selector”, in parenthesis, followed by a period, with a command or statement defining the action following the period.  The selectors are in quotes; the action commands aren’t in quotes, although their arguments typically are.  The general format of a jQuery statement looks like this:

$("select_something").do_something('argument 1","argument 2", etc.)

Using :contains()

Here’s the basic syntax for using the :contains() selector:

$("some_selector:contains(some_text)").some_action("some_argument");

Where some_selector is a selector that defines the type of element  —  typically, an HTML formatting tag, such as <p>, <li>, etc., without the <> brackets: “p:contains(some_text)”, which looks for all paragraph HTML elements (tagged with <p>…</p>) that contain the string “some_text”, “li:contains(some_text)”, which does the same thing for list HTML elements  (tagged with <li>…</li>)etc.
some_action is a jQuery action, which will operate on all elements which meet the selection criteria.

Pick A Line

Below is a stripped-down but functional example of the :contains() selector in operation:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p:contains(right)").css("font-style","italic");
});
</script>
</head>
<body>
<p>This is the right line.</p>
<p>This is the wrong line.</p>
</body>
</html>

If you copy the above code, paste it into a text file, give the file the extension .hem, and open it in a browser, it should produce the following output:

This is the right line.
This is the wrong line.

How It Works

First of all, note that the page links to an online source for the jQuery library; it could just as easily link to a local instance, but it must link to some version of the jQuery library.  Next, note that the  :contains() selector is part of a function which serves as an argument for the .ready() method.  The .ready() method checks to see if the document (i.e., the HTML page) has been loaded; after it is fully loaded, the function contained in the .ready() method’s argument will run.  Using jQuery operations as arguments for the .ready() method ensures that the contents of the page will be available when they run.

Searching For The Text

Now look at this line:

$("p:contains(right)").css("font-style","italic");

Let’s pick it apart.  First, note the $. Since you’re already linked to the jQuery library, the $ tells you that whatever follows will be a jQuery command.  Immediately following (between the first set of parentheses) is the selector, (“p:contains(right)”), which in this case really consists of two selectors; note that the entire selector argument is in quotes.  The first selector is “p”, which tells jQuery to look for all text contained within paragraph tags (<p>…</p>.  The second selector in the :contains() selector.  In this case, the search test is “right”.  Taken altogether, “p:contains(right)” tells jQuery to look for all HTML paragraph elements that contain the string “right”.

Taking Action

Now let’s take a lot at the second half of the line.  The .css() method is the action to be taken when jQuery find the HTML elements that contain the search string.  The arguments for the .css() method are standard CSS properties; again, note that they are in quotes.  In this case, they simply say to set the fond style to italic.  There are a variety of jQuery methods which can be used with the :contains() selector; they can include lengthy and complex arguments, including functions, and as discussed below, long strings of HTML code.

Making It A Little More Functional

Can we make our sample code a little more interactive?   Let’s place the :contains() selector in a jQuery-style button function, and give the user a choice:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".rght_btn").click(function(){
     $("p:contains(right)").css("font-style","italic");
  });
  $(".wrng_btn").click(function(){
     $("p:contains(wrong)").css("font-style","italic");
  });
});
</script>
</head>
<body>
<button class="rght_btn">Pick the right line</button>&nbsp;&nbsp; 
<button class="wrng_btn">Pick the wrong line</button>
<p>This is the right line.</p>
<p>This is the wrong line.</p>
</body>
</html>

Now the selectors and their subsequent .css() methods only go into action after the user clicks on one of the buttons.  Since the action taken is now in response to a user action, we might want to make the response a bit more dynamic:

$(".wrng_btn").click(function(){
     $("p:contains(wrong)").fadeOut(3000);

Now, instead of being displayed in italics, the “wrong” line will fade out completely, taking 3,000 milliseconds to disappear.  You could also use the .hide() method to achieve a similar effect.  The .fadeToggle() and .hideToggle() methods will fade the selected element in or out, depending on its current state.

Let’s Get Dynamic

You can also combine the :contains() selector with the .html() method to produce some on-the-spot dynamic web content.  Clicking on either button replaces the target HTML element with an entire HTML-formatted list:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".rght_btn").click(function(){
     $("p:contains( favorite)").html("<i>These</i> are a few of my favorite things: 
<ul><li>Roses,and</li><li>Rainbows, and</li><li>The Creature From The Black Lagoon</li></ul>");
  });
  $(".wrng_btn").click(function(){
     $("p:contains(unfavorite)").html("<i>These</i> are a few of my <i>un</i>favorite things:
<ul><li>Hangnails, and</li><li>Ingrown toenails, and</li><li>Phone batteries at 1%</li></ul>");
  });
});
</script>
</head>
<body>
<button class="rght_btn">My Favorite Things</button>&nbsp;&nbsp; 
<button class="wrng_btn">My Unfavorite Things</button>
<p>My favorite things.</p>
<p>My unfavorite things.</p>
</body>
</html>

Note that the first selector, (“p:contains( favorite)”), includes a space before the target text.  if it didn’t then clicking on the first button would select both lines, and replace them with the same text, since they both contain the string “favorite”.  Adding a leading space allows us to distinguish between the stand-alone word “favorite” and the string “favorite” contained in the word “unfavorite”.

There’s a lot more that you can do with jQuery, of course, and you can find plenty of online classes, from beginning to advanced, where you can learn much more about jQuery, about JavaScript, and about web design and programming in general.