Creating a Custom jQuery Selector

This isn't a new topic, but I had the need to create a custom jQuery selector today, so I thought I'd share. Whether you are a jQuery newbie or seasoned pro, you know that jQuery has very powerful selectors. In addition to the class and id selectors, there are over 30 selection expressions that use the colon syntax (:first, :even, :hidden, :input, etc.). If one of the existing selectors doesn't fit your needs, jQuery provides you the flexibility to create your own!

In my situation, I was looking for a selector that would allow me to do an exact search. The scenario: A user enters a value in a text box and submits. The value entered is then used to search a multiple select element for an option element with a text node that is an exact match (case-insensitive).

My solution:

jQuery.extend(jQuery.expr[':'], {
	exactIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase() == (m[3]).toLowerCase()"

If you wanted a case-sensitive selector:

jQuery.extend(jQuery.expr[':'], {
	exact: "a.textContent||a.innerText||jQuery(a).text()||'' == m[3]"

The JavaScript implementation:

$("#detail form.find").bind("submit", function (e) {
	 // cancel the submit

	// get the search value
	var q = $("#detail form.find input.query");

	// look for a match using the custom selector - only return the first one
	var result = $("#detail select.fields option:exactIgnoreCase(" + q.val() + "):first");

	// if a match was found, select that field (option). Clear the value and focus.
	// otherwise, add a visual clue that nothing was found
	if (result.length > 0) {
		result.attr("selected", true);
	else {

Pretty cool, huh!?! Now, try it out for yourself. Here's a template that will help get you started:

jQuery.extend(jQuery.expr[':'], {

To get samples of what goes in the EXPRESSION_RULE part, open up the jQuery source, look for "expr: {", then study all of the current expressions in the "":": {" section of the code.

Have you written any custom selectors that you'd like to share?


1 Comment

  1. September 25, 2008 @ 8:02 am #

    how can i make this customization for attr selectors like tag[attr*='something']? my aim is to create a by attribute case-insensitivite selector.

Leave a Comment

Sorry, comments are closed. You can contact me directly, if you like.

Eric Martin