Tuesday, September 20, 2011

Jquery add Custom Selectors

This is another one that has been talked about a lot in the development community, so you may have this already figured out. If not, get ready because this will open some whole new windows for jQuery efficiency. The short story is, jQuery allows us to extend its expression object, which means we can add whatever custom selectors we want. For example, say we wanted to add a selector version of the isChildOf() method we wrote earlier:

$(function(){ 
     jQuery.extend(jQuery.expr[':'], { 
        'child-of' : function(a,b,c) { 
               return (jQuery(a).parents(c[3]).length > 0); 
        }
     }); 

     //'child-of' is now a valid selector: 
     $("li:child-of(ul.test)").css("background","#000"); 
});

No comments:

Post a Comment