Home >Web Front-end >JS Tutorial >How Can I Dynamically Manage Element Classes in JavaScript?
Modern HTML5 Techniques for Class Manipulation
Modern browsers support the classList property, which provides convenient methods to add, remove, or toggle classes without needing external libraries:
document.getElementById("MyElement").classList.add('MyClass'); document.getElementById("MyElement").classList.remove('MyClass'); if ( document.getElementById("MyElement").classList.contains('MyClass') ) document.getElementById("MyElement").classList.toggle('MyClass');
Cross-Browser Solutions
To replace all existing classes with new ones, use className:
document.getElementById("MyElement").className = "MyClass";
Append a space and the new class name:
document.getElementById("MyElement").className += " MyClass";
Use a regular expression replace:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g , '');
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
Event Handling
You can assign these actions to onclick or other events by:
<button onClick="changeClass()"></button>
document.getElementById("MyElement").addEventListener('click', changeClass);
JavaScript Frameworks and Libraries
Frameworks and libraries simplify these tasks, such as jQuery:
$('#MyElement').addClass('MyClass'); $('#MyElement').click(changeClass);
The above is the detailed content of How Can I Dynamically Manage Element Classes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!