jQuery: Change the Class Name of a Specific DOM Element based on ID
This question addresses a common scenario where we need to modify the class name of a specific td element within a web page. Our goal is to achieve this programmatically from within the click event handler of another DOM element.
Solution using jQuery:
jQuery provides multiple methods for manipulating the class attribute of an HTML element.
Setting the Class (Replace Existing Class):
To set the class name entirely, regardless of its previous value, use the .attr() method:
$("#td_id").attr("class", "newClass");
Adding a Class (Append to Existing Class List):
If you wish to add a class while preserving any existing classes, use the .addClass() method:
$("#td_id").addClass("newClass");
Toggling Classes (Switch Between Classes):
For a convenient way to swap classes, use the .toggleClass() method:
$("#td_id").toggleClass("change_me newClass");
These methods allow us to dynamically change the class name of the target td element based on its ID, enabling us to modify the element's styling programmatically.
The above is the detailed content of How to Change a TD Element's Class Using jQuery Based on its ID?. For more information, please follow other related articles on the PHP Chinese website!