How to change an element's class with JavaScript?

Tutorial with code examples on how to change an element's class using JavaScript
27 September 2017   10541

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

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');

Unfortunately, these do not work in Internet Explorer prior to v10. 

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

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

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

Assigning these actions to onclick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'") this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:

<script type="text/javascript">
    function changeClass()
    {
        // Code examples from above
    }
</script>
...
<button onclick="changeClass()">My Button</button>

The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
    function changeClass()
    {
        // Code examples from above
    }

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

 

Frontend News Digest 3 -9.08

Learn this week's latest news and updates of JavaScript, CSS, PHP and related technologies
08 August 2019   461

Greetings! I hope your week went great! Here's new Frontend news digest.

In this digest, you will learn how to improve your procedural code, how to deploy apps to to IBM cloud with Tekton, how to use Immer to manage your React state and much more!

Guides

  • Trigger Firebase Storage Image Resize with Cloud Functions

Tutorial on creating an imager resizer triggered by Firebase Storage

  • Using pipe and compose to improve procedural code

According to the creator, this guide will sohw you how to use pipe and compose to improve the way we write procedural code.

  • Deploying Applications to IBM Cloud Kubernetes via Tekton

This article talks about Tekton, an open-source framework for creating CI/CD systems, and explains how to deploy and use it on the IBM Cloud Kubernetes service

  • Quick Gulp Cache Busting

This tips will allow you to improve your work with Gulp

  • Using Immer for React State Management

Learn how Immer can help you to operate React states

Article

  • Laravel Cloud Source Code on GitHub

Author believes that is a chance to get a glimpse of an application written by the creator of Laravel

Updates

  • Calendario

Library allowing to create flexible calendars

  • Symphony

According to the creators, 113 pull requests were merged (79 in code and 34 in docs) and 55 issues were closed (43 in code and 12 in docs)

Video

  • The Date Object - Getting, Setting & Formatting Dates in JavaScript - Tutorial

  • Simple Slide Show in JavaScript | JavaScript exercises