Alan Coromano
Alan Coromano

Reputation: 26008

Add/remove/replace the class for html element

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?

Upvotes: 0

Views: 308

Answers (7)

Jai
Jai

Reputation: 74738

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

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173542

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')

Upvotes: 1

ferdyh
ferdyh

Reputation: 1445

$('#elementId').addClass('className');
$('#elementId').removeClass('className');

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

Upvotes: 1

SachinGutte
SachinGutte

Reputation: 7055

Use addClass and removeClass

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

$("div#uniqeId").removeClass("firstClass");
$("div#uniqeId").addClass("Some_Other_Class");

Upvotes: 1

Osiris
Osiris

Reputation: 4185

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

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

Upvotes: 1

Mortalus
Mortalus

Reputation: 10712

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";

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

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

Upvotes: 1

Related Questions