: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("word1"), #div:contains("word2"), #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:
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.