Ninja Patching jQuery

April 2, 2008 Pivotal Labs

Jonathan and I love jQuery’s extended psuedo-selectors:

  • :input – Matches all input, textarea, select and button elements.
  • :text – Matches all input elements of type text.
  • :password – Matches all input elements of type password.
  • :hidden – Matches all elements that are hidden, or input elements of type * “hidden”.
  • :visible – Matches all elements that are visible.
  • and so on

These aren’t actually part of the CSS spec, but they’re incredibly useful and can be chained:

$(':input:visible') // => finds all visible inputs

We wanted to customize the behaviors of :text and :visible:

  • We wanted :text to return both <input type="text"> AND <textarea>
  • We wanted :visible to return elements that aren’t directly display:none or visibility:hidden, nor are their parents display:none or visibility:hidden

So, we decided to customize this behavior:

jQuery.extend(jQuery.expr[":"], {
  text    : "(a.tagName=='INPUT' && a.type=='text') || (a.tagName=='TEXTAREA')",
  visible : '"hidden"!=a.type && jQuery.css(a,"display")!="none" && jQuery.css(a,"visibility")!="hidden" && (jQuery(a).parent(":hidden").size() == 0)',
  hidden  : 'document != a && ("hidden"==a.type || jQuery.css(a,"display")=="none" || jQuery.css(a,"visibility")=="hidden" || (jQuery(a).parent(":hidden").size() > 0))'

So how would you like to ninja-patch jQuery’s custom pseudo-selectors?

About the Author


My Feed
My Feed

For the last several months I've been producing a Shared Items feed in Google Reader that some of my friend...

Evan Phoenix at Mountain West Ruby Conf
Evan Phoenix at Mountain West Ruby Conf

I just attended (and thoroughly enjoyed) the Mountain West Ruby Conf, where Evan Phoenix gave a powerful ke...

SpringOne 2021

Register Now