Home >Web Front-end >JS Tutorial >How Can I Efficiently Change Element Classes Using JavaScript?
Modern browsers support the classList property, which provides methods for manipulating classes:
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');
Use className to set all classes:
document.getElementById("MyElement").className = "MyClass";
Append a space and the new class:
document.getElementById("MyElement").className += " MyClass";
Use a regex replace:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '');
Use the same regex for checking:
if (document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/))
Avoid using inline JavaScript in HTML attributes. Instead, create a function and call it in the onClick attribute:
<script> function changeClass() { // Action code } </script> <button onClick="changeClass()">My Button</button>
Or with addEventListener:
<script> window.onload = function() { document.getElementById("MyElement").addEventListener('click', changeClass); } </script> <button>
$('#MyElement').addClass('MyClass'); $('#MyElement').removeClass('MyClass'); if ($('#MyElement').hasClass('MyClass'))
Toggle a class:
$('#MyElement').toggleClass('MyClass');
Assign a click event:
$('#MyElement').click(changeClass);
The above is the detailed content of How Can I Efficiently Change Element Classes Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!