0

I'm curious about how can I add/remove class to html element? It seems to be a very simply operation. But it turned out that the method removeClass was not found for some reason.

So what I need to do is replace or remove an old one and add a new one to an element. How can I do that?

Alan Coromano
  • 22,006
  • 44
  • 122
  • 184

7 Answers7

1

Use AddClass to add class, removeClass to remove, toggleClass to toggle (removes class if exists or adds if does not exist) :)

karaxuna
  • 25,822
  • 11
  • 76
  • 111
1

If you use jQuery make sure it is loaded before your script and then use like this:

$('p').removeClass('myClass yourClass') // remove class
$("p").addClass("myClass yourClass");   // add class

if you want to use pure JS here you are : How do I add a class to a given element?

var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Community
  • 1
  • 1
Mortalus
  • 10,046
  • 9
  • 60
  • 108
  • 1
    The pure js version is starting to show its age; more browsers are now supporting [`classList`](https://developer.mozilla.org/en-US/docs/DOM/element.classList). – Ja͢ck Apr 17 '13 at 08:34
1

The removeClass method is included in jQuery, unless you've overridden it.

$("#someElement").removeClass("someclass");

Osiris
  • 4,047
  • 2
  • 17
  • 49
1

Use addClass and removeClass

<div class="firstClass" id="uniqeId"></div>

$("div#uniqeId").removeClass("firstClass");
$("div#uniqeId").addClass("Some_Other_Class");
SachinGutte
  • 6,438
  • 5
  • 32
  • 57
1
$('#elementId').addClass('className');
$('#elementId').removeClass('className');

See: http://api.jquery.com/category/manipulation/class-attribute/

ferdyh
  • 1,220
  • 2
  • 10
  • 27
1

Since your question is tagged with , there are two functions you can use:

  1. $(element).removeClass('oldclass')

  2. $(element).addClass('newclass')

Without jQuery and on modern browsers you can work with the classList property:

element.classList.remove('oldclass')

element.classList.add('newclass')
Ja͢ck
  • 161,074
  • 33
  • 239
  • 294
1

You can use .toggleClass() to add/remove simultaneously, i mean switch from one class to another:

Description from the docs

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

if this is your html:

<div class="aaa">Some text.</div>

then this script:

$('div.aaa').toggleClass('bbb');

will output like this:

<div class="aaa bbb">Some text.</div>

Or if you do this:

$('elem').toggleClass('aaa bbb');
     //--------------------^^^---here this class will be added/removed
Community
  • 1
  • 1
Jai
  • 71,335
  • 12
  • 70
  • 93