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   12327

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 18 - 24.01

How to turn a procreate drawing into a web animation, how to self-hos your web fonts, giant fines for privacy breach in EU and more
24 January 2020   90

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

Learn about the new browser in-development called Flow, which has a completely new multi-threaded rendering engine, Google is stopping the support for data-vocabulary, NodeJS update and other intersting posts, guides, updates and more are waiting for your attention in this digest.

Guides

  • How to Turn a Procreate Drawing into a Web Animation

Great tiny tutorial for those who use the popular iOS drawing app for creating something for your website

  • Understanding the “Initial”, “Inherit” and “Unset” CSS Keywords

Deep guide for the CSS newbies, but even skilled frontenders can find something interesting

  • How To Self-Host Your Web Fonts

Learn how to self-host web fonts so you’re not rely on Google

Articles

  • New browser on the block: Flow

An interview with Piers Wombwell, lead developer of Flow, a new browser that is being developed and it has a completely new multi-threaded rendering engine (no relation to WebKit, Gecko, or Blink)

  • Fines for European privacy breaches reach 114 million euros: report

Don't break the law

  • Sunsetting support for data-vocabulary

Starting from April 6, the data-vocabulary markup will no longer be eligible for Google rich result features

Update

  • Playwright

Node lib to automate the Chromium, WebKit and Firefox browsers

  • AVA

Test runner for Node.js

  • Node v13.7.0 (Current)

Another update for superpopular tool

Video

  • dotJS 2019 - Bert Belder - Deno