I love jQuery. Well, love is a big word actually, let’s say that I like it much more than plain Javascript. It allows me to code quicker, at a higher level and, most importantly, to focus on what I want to do more than on how I have to do it.

Having said this, I don’t use Javascript/jQuery as often as other programming languages, so I am not as fluent as with PHP for example, and sometimes I find myself having to go back to the basics. I have recently had to find a way to use the :contains operator to look for multiple words inside <div> elements on a webpage, but the jQuery documentation doesn’t include any examples for these scenarios. Luckily, jQuery allows you to do this very quickly. Here’s how.

If you want to iterate over all <div> elements on a page, you might be tempted to think about using a foreach loop, but it turns out this is not necessary as the jQuery selectors will act on all elements by default.

Look for one or more words (logical OR)

If you want to look for a word in a predefined sets of words, and you just want to do something on the <div> if you find at least one of those words (word1 OR word2), you can use multiple :contains operators separated by a comma:

   #div:contains("word3")').css('backgroundColor', 'yellow');

Look for all the selected words (logical AND)

If you want to act on an element only if you find all the words you have listed, you can simply concatenate multiple :contains operators instead:

$('#div:contains("word1"):contains("word2"):contains("word3")').css('backgroundColor', 'yellow');

Obviously, both of these approaches do not scale very well: if you have lots of words you want to monitor, you would be better off using some other type of structure (an array with all the words perhaps), but if your needs are just as simple, this is the quickest way I know to look for multiple words inside an element.