-4

I have a sample code like

<td>
  <span class="abc def">Deleted</span>
</td>

I have a button. If I click on the button I want to change my class name abc def to xyz pqr

Greedo
  • 3,438
  • 1
  • 13
  • 28
Rajendra Bar
  • 49
  • 1
  • 8
  • 4
    and what have you tried so far? any efforts except posting on stackoverflow? – jarvo69 Sep 07 '21 at 09:13
  • Does this answers your question? https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript – Supritam Sep 07 '21 at 09:17

2 Answers2

-1

You can access the classes of an elment with classList:

document.getElementById("btn").classList = "xyz pqr";
<td>
  <span id="btn" class="abc def">Deleted</span>
</td>
Greedo
  • 3,438
  • 1
  • 13
  • 28
  • classList is DOM token list and you can not manually change the class using equals. You can use **add() remove() replace()** instead – Amini Sep 07 '21 at 09:19
-2

You can either use

a) Element.className (https://developer.mozilla.org/en-US/docs/Web/API/Element/className)

let el = document.getElementById('item');

if (el.className === 'active'){
  el.className = 'inactive';
} else {
  el.className = 'active';
}

OR

b) Element.classList (https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)

const div = document.createElement('div');
div.className = 'foo';

// our starting state: <div class="foo"></div>
console.log(div.outerHTML);

// use the classList API to remove and add classes
div.classList.remove("foo");
div.classList.add("anotherclass");

// <div class="anotherclass"></div>
console.log(div.outerHTML);

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

console.log(div.classList.contains("foo"));

// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");

// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

// replace class "foo" with class "bar"
div.classList.replace("foo", "bar");
  • ``el.classList === 'foo'`` won't work cause classList is DOM token list and you must use **contains()** instead. https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains – Amini Sep 07 '21 at 09:18