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   2933

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>

 

BIF-2018 to be Held This Week

Representatives of the IT community will gather again in the Belgorod Philharmonic to discuss prospects for the development of the IT industry and modern trends in digital solutions
10 September 2018   365

On September 15, Belgorod will host the second IT-forum, which will bring together more than a thousand participants from different regions of the country. As in the past year, the central part of the event will be held in the Belgorod Philharmonic.

BIF2017BIF-2017

The primary goal of the forum is to show that it is possible to work in our region and at the same time create products that will be relevant all over the world. And every year it becomes easier. In IT there are no boundaries, they exist only in the minds, but these borders can also be erased, and this is how the forum helps. At such events, teams from different cities are formed and they can create joint products.

 

Yevgeny Miroshnikov

Head of the department of information technologies and communications of the regional governor's administration

The educational program has changed this year regarding the format of the presentation and the time of the speeches. Participants now can dive into the topic in a shorter time. The program is almost formed - representatives of VKontakte, GetTaxi, Sberbank-Technologies, Alfa-Bank, Dodo Pizza, Internet Initiatives Development Fund and many other companies will make presentations.

Last year, the forum participants wondered why there was no design course. Indeed, there were only a couple of reports from designers in the digital section. We heed the wishes of the participants and this year we are preparing a full-fledged direction in design, inviting experts working on projects in Artemiy Lebedev's studio, Alfa Bank and other top technological companies.

 

Dmitry Zadochin

Head of the IT Development Center of the Belgorod Informational Fund

In addition to design, the flexible methodologies of project management - Agile and Scrum, will also be discussed in a separate area. For civil servants, There is also a separate section for civil servants dedicated to smart cities.

There is today much talk about smart cities and how information technologies change different spheres of life. At the same time, "smart city" is a collective concept, because there is no clear definition of what it is. At a particular section of the Smart City Day, we'll talk about what technologies help make the life of the city better. The main areas will be health, transportation, and culture.

 

Yevgeny Miroshnikov

Head of the department of information technologies and communications of the regional governor's administration

Yevgeny also added that there is an ambitious goal regarding smart roads on the state level - the number of road deaths must be zero. The forum is planned to hold a council under the governor for innovative technological development, where application solutions will be presented to make the roads safe. There are already unique developments in Belgorod that will soon be announced.

After the completion of the educational program for the forum participants will perform a concert orchestra of wind instruments under the leadership of Yuri Merkulov. And there will be an afterparty in one of the city’s restaurants after the symphony concert.

The event will begin at 10:00 with a panel discussion, after which the speeches will start in five sections.

More information:

  • Website
  • ‎Vkontakte