Questions tagged [addclass]

addClass is a method on jQuery objects that adds a CSS class to the selected elements.

addClass is a method on jQuery objects that adds a CSS class to the selected elements. Unlike setting className, addClass will not remove any existing classes.

Example

To select all paragraphs that are the first child of the parent and add the first class to them:

$('p:first-child').addClass('first');

Further reading

1227 questions
122
votes
4 answers

Check if class already assigned before adding

In jQuery, is it recommended to check if a class is already assigned to an element before adding that class? Will it even have any effect at all? For example: When in doubt if class baz has already been assigned to…
Muleskinner
  • 14,150
  • 19
  • 58
  • 79
113
votes
3 answers

Should I use "hasClass" before "addClass"?

I have come across the following script which checks whether an element has class a, and if not, adds it: if (!$("div").hasClass("a")){ $("div").addClass("a"); } As jQuery won't add the class if it already exists, this could be changed…
Curtis
  • 101,612
  • 66
  • 270
  • 352
103
votes
6 answers

Remove all classes except one

Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:
Let's say that with some clicks and other things, the div gets a lot of classes
DarkGhostHunter
  • 1,521
  • 3
  • 12
  • 23
41
votes
10 answers

addClass and removeClass in jQuery - not removing class

I'm trying to do something very simple. Basically I have a clickable div 'hot spot', when you click that it fills the screen and displays some content. I achieved this by simply changing the class of div, removing 'spot' and adding 'grown' and…
rhinoceros1
  • 411
  • 1
  • 4
  • 4
30
votes
7 answers

How do I add a new class to an element dynamically?

Is there any way to add a new CSS class to an element on :hover? Like for jQuery, but translated into CSS: $(element).addClass('someclass');
itsme
  • 48,972
  • 96
  • 224
  • 345
29
votes
4 answers

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

Looking to change the border color on a box.. ..when the user mouses over/out.. Here's the attempted code.. Needs Work! JQuery: