I want to change the class of a td tag given the td tag's id:
<td id="td_id" class="change_me"> ...
I want to be able to do this while inside the click event of some other dom object. How do I grab the td's id and change its class?
To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.
document. getElementById('myElement'). className = "myclass"; Example 1: In this code change the class of the button from “default” to “changedClass” using the onclick event which in turn changes the background color of the button from RED to GREEN.
To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)
Using jQuery
You can set the class (regardless of what it was) by using .attr()
, like this:
$("#td_id").attr('class', 'newClass');
If you want to add a class, use .addclass()
instead, like this:
$("#td_id").addClass('newClass');
Or a short way to swap classes using .toggleClass()
:
$("#td_id").toggleClass('change_me newClass');
Here's the full list of jQuery methods specifically for the class
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With