jQuery Extension: radioClass() method

by Tim Banks

I recently ran into a method in the Ext javascript library called radioClass.  This method will add one or more CSS classes to an element and remove the class(es) from the siblings of the element.  I found that this would be helpful in jQuery since I find myself doing something similar often:


$("li").addClass("selected").siblings().removeClass("selected");

I wrote the following extension method in jQuery to reduce the amount of code.

Code:


$.fn.extend({
     radioClass: function(c) {
     return $(this).addClass(c).siblings().removeClass(c).end();
}
});

Usage:


$("li").radioClass("selected");

View Demo

Tags: , , ,

« »

3 Responses to “jQuery Extension: radioClass() method”

  1. jQuery Extension: radioClass() method | Tim Banks Says:

    [...] out the blog post on the Lanit Development Blog – jQuery Extension: radioClass() method This entry was posted on Thursday, September 3rd, 2009 at 8:08 am. You can follow any responses [...]

  2. John Pasquet Says:

    That will come in handy.

  3. Charles Phillips Says:

    Found this while googling for my own, looks like you and I had the same idea a month apart:

    http://code.doublerebel.com/jQuery/jquery.radioclass.js

    Mine has Ext”s array compatibility, if you need it.

Leave a Reply

NoFollow Plugin made by Web Hosting