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
	 e.preventDefault();

	// 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);
		q.removeClass("requiredError").val("").focus();
	}
	else {
		q.addClass("requiredError");
	}
});

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

jQuery.extend(jQuery.expr[':'], {
	EXPRESSION_NAME: "EXPRESSION_RULE"
});

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 thought on “Creating a Custom jQuery Selector”

Comments are closed.

Scroll to Top