How to Change an Element's Class Using JavaScript
Responding to various events like onclick, JavaScript provides several techniques for altering an HTML element's class.
Modern HTML5 Techniques
For modern browsers that support classList, the following methods offer a simple approach:
Cross-browser Solutions
For wider browser compatibility:
To Change All Classes
To Add a Class
To Remove a Class
To Check if a Class is Applied
Assigning Actions to onClick Events
To separate HTML and JavaScript, it's recommended to use functions:
HTML
<button onClick="changeClass()">My Button</button>
JavaScript
function changeClass() { // Code examples from above }
Alternatively, using addEventListener:
window.onload = function() { document.getElementById("MyElement").addEventListener('click', changeClass); }
JavaScript Frameworks and Libraries
Libraries like jQuery simplify these tasks:
To Change Classes
$('#MyElement').addClass('MyClass'); $('#MyElement').removeClass('MyClass'); if ($('#MyElement').hasClass('MyClass'))
Shortcut for Adding/Removing a Class
$('#MyElement').toggleClass('MyClass');
Assign Function to Click Event
$('#MyElement').click(changeClass);
The above is the detailed content of How Do I Change an Element's Class Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!