> jQuery.fn.swapClass = function(c1, c2){
> return this.each(function(){
> var t = $(this);
> ( t.is('.'+c1)) ?
> t.addClass(c2).removeClass(c1) : t.addClass(c1).removeClass(c2);
> });
> }
> Also i would like to know if this is the most efficient this code could
be.
As written it will add c2 when neither c1 nor c2 were originally classes of
the element. If it's really just swapping classes I would say it shouldn't
add c2 unless c1 was already there, but hey it's your swapClass. :) If both
c1 and c2 are present, it will remove c1 and leave c2. (jQuery correctly
handles a redundant addClass.)
The source is shorter but slower than using the element's className property
directly. You're creating a new jQuery object for each element and calling
three methods on it. Each of those methods call several other methods that
end up reading each element's className property a total of six times and
writing it twice. If you're not using swapClass a lot, it won't make any
difference because "slower" might (hypothetically) be 50 milliseconds
instead of 5 milliseconds. Sure it's 10 times slower, but it's still plenty
fast.
If this really was a bottleneck, an element's className is a well-documented
DOM property and you can get the useful RegExps from jQuery's className
support. A performance middle ground would be to use
jQuery.className.has/.add/.remove methods directly. They aren't marked
@private, although that may be an oversight. Neither optimization would be
worthwhile (IMO) unless it was a proven bottleneck.
I tried to think of a fully chained implementation that didn't require the
.each "loop" but it's tricky because you need to select all the c2 class
elements before you swap c1 to c2. This is the closest I can get, and it
doesn't seem elegant (untested).
jQuery.fn.swapClass = function(c1, c2){
var c2j = $('.'+c2, this);
this.find('.'+c1).addClass(c2).removeClass(c1).end();
c2j.addClass(c1).removeClass(c2);
return this;
};
I thought of with a single-chain version but it (ab)uses .pushStack which is
marked @private.
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/