Oct 27, 2010
Find elements that don't contain a string
Posted in "development"
If you want to see the really cute kitty that's underneath the image above jump to this link: http://fillip.ca/content/have-you-seen-this-kitten (I know you want to)
The Problem:
Now that's out of the way. I had an issue the other day with finding an element that didn't contain a certain "string". If you've never heard about the jQuery filter :contains you may be unaware that you can find an element based on if it contains a certain string.
A Solution:
The work around to finding an element that does not contain a certain string is a little complex in it's notation:
$("div:not(':contains(test)')");`</pre>
This can also be written like so:
<pre class="brush:js">`$("div").not(':contains(test)');`</pre>
Here I've used jQuery's **.not()** method to find the opposite of the expresion "**:contains('test')**". This works, but doesn't look very nice nor is it easy to read for beginners.
## A Better Solution:
I didn't like how this looked or was named so I made a simple plugin that will do this exact same kind of logic but in a simpler manner. The plugin is called **:missing**. This filter is named and has the exact oppositie functionality as the **:contains** filter. An example use would be:
<pre class="brush:js">`$("div:missing(test)");`</pre>
## The Plugin code:
<pre class="brush:js">`jQuery.expr[':'].missing = function(elem, index, match) {
return (elem.textContent || elem.innerText || Sizzle.getText([elem]) || "").indexOf(match[3]) == -1;
}