Home > Web Front-end > JS Tutorial > How Can I Efficiently Change Element Classes Using JavaScript?

How Can I Efficiently Change Element Classes Using JavaScript?

DDD
Release: 2024-12-28 08:39:10
Original
682 people have browsed it

How Can I Efficiently Change Element Classes Using JavaScript?

How To Change Element Classes Using JavaScript Events

Modern HTML5 Techniques

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');
Copy after login

Simple Cross-Browser Solution

Changing All Classes:

Use className to set all classes:

document.getElementById("MyElement").className = "MyClass";
Copy after login

Adding an Additional Class:

Append a space and the new class:

document.getElementById("MyElement").className += " MyClass";
Copy after login

Removing a Class:

Use a regex replace:

document.getElementById("MyElement").className =
  document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '');
Copy after login

Checking for a Class:

Use the same regex for checking:

if (document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/))
Copy after login

Assigning Actions to onClick Events

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>
Copy after login

Or with addEventListener:

<script>
  window.onload = function() {
    document.getElementById("MyElement").addEventListener('click', changeClass);
  }
</script>
<button>
Copy after login

JavaScript Frameworks and Libraries

jQuery Examples

$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ($('#MyElement').hasClass('MyClass'))
Copy after login

Toggle a class:

$('#MyElement').toggleClass('MyClass');
Copy after login

Assign a click event:

$('#MyElement').click(changeClass);
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template