Filter elements by pattern jQuery.

The need was pretty simple : "Find the elements that contain a particular word and display them and hide others" Along with my friend Kambfhase we came with a simple hack to achieve this, well this in itself is very simple to be a jQuery plugin but can be a part of huger system.

Code :

(function($) {
  $.fn.filterByPattern = function(string){
    var regex = new RegExp( string, "ig");
 
    return this.hide().filter(function(){
        return regex.test($(this).text());
    }).show();
};
}(jQuery));

Usage:  $("div").filterByPattern("python")

Extra : Used the same at codingconfessional.com to filter out the needed, for example :   $("div.confession").filterByPattern("python") will show all the python confessions ;)

Update 0: Why was contains() not used? Issue 278

Share this