[jQuery] hasClass()? (also toggleClass, removeClass)

[jQuery] hasClass()? (also toggleClass, removeClass)

I was looking for a hasClass() as well, and the solution given in the
thread isn't exactly terse - nor what I wanted. I have a single
element, e.. and I want to see if that element hasClass('selected') ..
I tried various forms of CSS querying like :
$('*.selected', e).each( function() { alert('yup'); } );
Without any luck at all. I suppose I just couldn't figure out the
right CSS or XPath query to use.. so I solved it my own way.
I wrote this small function and added it to my copy of jquery.js
hasClass: function(c) {
return ($.hasWord($a,c));
},
which I can use like so:
if ( $(e).hasClass('selected') )
alert('yup');
That solves this one particular need I have, and I don't expect to use
it in chained situations... maybe someone can make it better, so that
it works more in the spirit of the other code.
I also rewrote toggleClass and removeClass because I had some quirks
with the RegularExpressions on occasion which I couldn't pin down.
Since the rewrite, I've never had a problem :
removeClass: function(c) {
return this.each(function(){
if ($.hasWord(this,c)) {
var classNames = this.className.split(/\s+/) || [];
var classIndex = classNames.indexOf(c);
classNames.splice( classIndex, 1 );
this.className = classNames.join(' ');
}
});
},
toggleClass: function(c) {
return this.each(function(){
if ($.hasWord(this,c)) {
var classNames = this.className.split(/\s+/) || [];
var classIndex = classNames.indexOf(c);
classNames.splice( classIndex, 1 );
this.className = classNames.join(' ');
} else
this.className += ( this.className.length > 0 ? "
" : "" ) + c;
});
},
.. not minimalist, but it seems to work.
> my brain clearly wasn't working yesterday. thanks. that should've
> been obvious... that'll teach me to work too much.
>
> R
>
> On May 23, 2006, at 3:09 AM, Kelvin Luck wrote:
>
> > Do you mean:
> >
> > $('li.foo')
> >
> > ? That will give you all li's with a class of "foo". If you want to do
> > something to each of them you could do:
> >
> > $('li.foo').each(function()
> > {
> > alert(this); // this is the current li instance
> > // do stuff
> > });
> >
> > Hope that helps,
> >
> > Kelvin :)
> >
> > Robb Irrgang


































































    • Topic Participants

    • don