Set class in jQuery

live627

  • Should five per cent appear too small / Be thankful I don't take it all / 'Cause I'm the taxman, yeah I'm the taxman
  • Posts: 1,670
Set class in jQuery
« on July 10th, 2012, 08:15 AM »
Is there an equivalent function in jQuery that does the same thing as className other than attr()?
A confident man keeps quiet.whereas a frightened man keeps talking, hiding his fear.

Nao

  • Dadman with a boy
  • Posts: 16,082
Re: Set class in jQuery
« Reply #1, on July 10th, 2012, 10:29 AM »
You mean .hasClass('class')...?
Or simply .is('.class')? (A bit slower though.)
If you want to assign a class, use .addClass('class') or .toggleClass('class'). The opposite is .removeClass('class').
If you want to get a list of all classes, you'll have to rely on $()[0].className or $().attr('class'), AFAIK.

live627

  • Should five per cent appear too small / Be thankful I don't take it all / 'Cause I'm the taxman, yeah I'm the taxman
  • Posts: 1,670
Re: Set class in jQuery
« Reply #2, on July 10th, 2012, 11:40 PM »
Hmm... okay. So there's no hidden magic function that I missed. Thanks anyway, Nao!

Nao

  • Dadman with a boy
  • Posts: 16,082
Re: Set class in jQuery
« Reply #3, on July 11th, 2012, 12:36 AM »
Well, there's nothing wrong is using className (or anything purely JS) even when jQuery equivalents are available. I usually choose to use jQ in these situations because the code is shorter and thus compresses better.

Speaking of which, I just finished rewriting Zoomedia... The code works much better, and is about 150 bytes shorter :D

live627

  • Should five per cent appear too small / Be thankful I don't take it all / 'Cause I'm the taxman, yeah I'm the taxman
  • Posts: 1,670
Re: Set class in jQuery
« Reply #4, on July 11th, 2012, 12:54 AM »
Same in my case... I need to set a class to multiple elements at once, and I can use JQ's .attr(), which saves me typing.