Monday, December 15th, 2008

Extending jQuery selectors with JavaScript

Category: jQuery


  1. // Flag images upon load:
  2. $('img').load(function(){
  3.     $(this).data('loaded',true);
  4. });
  6. // Extend expr:
  7. $.extend($.expr[':'],{
  8.     loaded: function(a) {
  9.         return $(a).data('loaded');
  10.     }
  11. });
  13. // Example of usage:
  14. alert( 'Images loaded so far: ' + $('img:loaded').size() );

This code is one example of how you can extend the selector experience in jQuery with simple JavaScript code.

James Padolsey takes us through this in a lot of detail, showing other examples including a simple “if the element is inline” selector, as well as well as tying into jQuery’s “data” functionality.

Posted by Dion Almaer at 6:15 am

3.8 rating from 50 votes


Comments feed TrackBack URI

Looking through his posts, James Padolsey is one very bright 18-year old.

Comment by StevenBlack — December 15, 2008

You know what would be great? If CSS had this kind of extensibility built in so that you could roll your own selectors then use them in CSS instead of just within Javascript.

Comment by okonomiyaki3000 — December 15, 2008

Leave a comment

You must be logged in to post a comment.