On Jan 13, 2007, at 9:52 PM, Miles Storey wrote:

> Hi, I'm just starting to use jQuery and, while I'm not much of a  
> coder, I love the way it works. I was developing a project using  
> the Prototype library, but after discovering jQuery I'm converting  
> everything. I'm finding it straightforward but I have a request for  
> a clarification on something.
>
> I have a function that branches depending on the class name of the  
> element that was passed to it.
>
> Using Prototype:
>
> function checkState(id) {
>   if ($(id).className == "something") { etc
>
> but in jQuery it doesn't work. It does work if I use:
>
> if ($(id).attr("class") == ""something") { etc
>
> I'm just wondering, as a beginner, if that would be the most  
> 'correct' way to do it.

Is "id" an ID? If so, you could use $('#id.something') and chain  
whatever methods you want onto it.

> Also, if I want to toggle the class name of an element between say  
> "active" and "inactive" what is the easiest way to do that? From  
> the documentation I see that addClass won't replace the existing  
> class so it looks like the best way is to use the attr(key,value)  
> method and do something like:
>
> $(id).attr("class", "active")
>
> It works, I'm just looking for 'best practise' advice.

IYou could do something like this:

   $(id).removeClass('inactive').addClass('active');

and this:

   $(id).removeClass('active').addClass('inactive');

Your approach will strip the id of any other classes that it might  
have as well. So, if the element were <div id="foo" class="inactive  
pretty">, you would be changing it to <div id="foo" class="active">,  
and you would be losing the "pretty."

By using .removeClass() and .addClass() you can be a little more  
precise.

>
> Thanks
> Miles
> _______________________________________________
> jQuery mailing list
> [email protected]
> http://jquery.com/discuss/


_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/

Reply via email to