CODE: jQuery’s :contains and White Space

Over the weekend I ran into one of those situations where it felt like I had found a bug in a very commonly used portion of a very commonly used piece of software (jQuery). Of course, 99.99% of the time when that happens, I’m wrong, not the software.

I recently started writing some Javascript and CSS to completely change the appearance of a web site I frequently use and make it look more modern and less cluttered. In the course of doing that I had call to use jQuery’s :containsselector. :contains allows you to select DOM elements which contain text. For instance, you would use a query like:

$('legend:contains("Options")')

to select this HTML:

<legend>Options</legend>

In an effort to make my code more readable, I’ve been trying to be careful and consistent about my use of whitespace – lots of it to help make code more readable. I started doing this in Perl but have carried it over to Javascript. So instead of the Javascript I quoted above, I wrote it as:

$( 'legend:contains( "Options" )' )

Note particularly the spaces around “Options”. If this were an ordinary Javascript function call those spaces would be fine. Instead, this is being parsed by jQuery’s Sizzle engine, where apparently the white space is not okay. This leads to the really unexpected outcome of :contains failing all over the place.

To be fair, jQuery and Sizzle never promised that white space would be okay here. I can’t claim this is a bug, just unexpected behavior.

Try it out with a jsfiddle.