0 votes
1 view
in Web Technology by (15.8k points)

How can I change a class of an HTML element in response to an on-click event using JavaScript?

1 Answer

0 votes
by (32.2k points)

Techniques for changing classes in Modern HTML5 is as follows: 

Modern browsers will be added in classList which provides methods to make it easier to manipulate classes without needing the 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');

But, the above code will not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. 

Simple cross-browser solution is as follows 

The standard JavaScript way to select an element is using document.getElementById("Id"), this is what the following examples use but you can obtain elements in other ways.

To change all classes for an element and to replace all the existing classes with one or more new classes, set the className attribute like this:

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

(You should use a space-delimited list to apply multiple classes.)

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

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

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

document.getElementById("MyElement").className =

   document.getElementById("MyElement").className.replace

      ( /(?:^|\s)MyClass(?!\S)/g , '' )

/* Code wrapped for readability - above is all one statement */

The explanation for the regex is as follows:

(?:^|\s) # This matches the start of the string, or any single whitespace character

MyClass  # The literal text for the classname to remove

(?!\S)   # Negative lookahead to verify the above is the whole classname

         # Ensures that there is no non-space character following

         # (i.e. must be end of the string or a space)

Here, the g flag will tell the replace to repeat as required, in case the class name has been added multiple times.

Try the code given below to check if the class is already applied to an element, the same regex used above for removing a class can also be used as a check as to whether a particular class exists or not:

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

Assigning the above actions to on click events:

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

The first step to achieve this is by creating the function and calling the function in the onclick attribute. 

Example:

<script type="text/javascript">

    function changeClass(){

        // Code examples from above

    }

</script>

...

<button onclick="changeClass()">My Button</button>

But, this will not be required to have this code in script tags, it also includes the JavaScript in a distinct file may be more appropriate. Another 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>

(Note: The window.onload part is required hence, the contents of that function are executed after the HTML has finished loading - without this, the element may not exist when the JavaScript code is called, so that line will fail.)

JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, but it's recommended to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when you are writing your code. Some people consider it overkill to add a ~50 KB framework for simply changing a class,

But, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, then it will be worth considering. (Note: A library is the set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties. The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too.

(Here, $ is the jQuery object.)

Try this to change Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

Additionally, jQuery provides the shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');

Use this for assigning a function to a click event with jQuery:

$('#MyElement').click(changeClass);

Or, use this for without needing an id:

$(':button:contains(My Button)').click(changeClass);

...