jQuery Content RegExp Selector

jQuery logo

One of jQuery’s best features is the ease with which it can be extended with simple plugins. This post on customizing jQuery selectors inspired me to write the following selector extension, which matches text content in the current element set with a regular expression. Remember how I said it was simple? More like effortless, you could easily squeeze this down into a half dozen lines or so if you were so inclined.  The only slightly difficult bit is figuring out what the “a”, “i” and “m” parameters mean in the jQuery selector source.  From the looks of things “a” is the element to match, “i” is the index in the list of matched elements, and “m” is the regexp match for the selector expression where “m[3]” is the value of the parameter supplied to the selector function.

[code lang="javascript"]
(function ($) {
     var match = function (a, i, m) {
         return RegExp(m[3]).test(a.textContent || a.innerText || $(a).text() || "");
     };

     var match_ignore_case = function (a, i, m) {
         return RegExp(m[3], 'i').test(a.textContent || a.innerText || $(a).text() || "");
     };

     $.extend($.expr[':'], {
                  containsmatch: match,
                  containsmatchi: match_ignore_case
              });
 })(jQuery);
[/code]

With the above code loaded, “:containsmatch(<regexp>)” and “:containsmatchi(<case insensitive regexp>)” will be added to jQuery’s already generous set of selectors. For example, [code lang="javascript"]$('p:containsmatchi(^the)')[/code] will case insensitively match any paragraph element with text content beginning with “the”.


About this entry