Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change class name

Tags:

jquery

css

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?

like image 900
aeq Avatar asked Aug 10 '10 19:08

aeq


People also ask

How can I replace one class with another in jQuery?

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.

Can we change class name in Javascript?

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.

How do you change the class of an element?

To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)


1 Answers

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.

like image 171
Nick Craver Avatar answered Sep 30 '22 15:09

Nick Craver