JavaScript Add,Remove,Toggle class
   Dec. 21st,2017
   Ismail Nassor Mbarack

Last week when I was in the office my workmate asked me a very simple question that became a little bit of a challenge to me, she asked me how to add/remove/toggle a CSS class with Vanilla JavaScript. I knew how to do it with jQuery and I often used it to add/remove/toggle classes but since we had to use pure JavaScript I had to go through some JavaScript documentation and found these three really awesome JavaScript built in functions that make life so easy. To add a class you simply need to use the add('class-name'), to remove you need to use the remove('class-name') and for toggling as you can guess it's simply toggle('class-name').These are very simple functions that work just like the way it is in jQuery but there aren't very popular for some reasons, but frankly speaking they are very powerful.

The example code goes as follows

<html>
<head>
	<title></title>
	<style>
		.my-test-class
		{
			color:red;
		}
	</style>
</head>
<body>
	<button id="my-btn">CLICK ME</button>
	<div id="my-id-selector">Some text for testing</div>
	<script>
		var myBtn=document.getElementById("my-btn");
		myBtn.addEventListener("click",function(){
			var myElement=document.getElementById('my-id-selector');
			myElement.classList.add('my-test-class')
		})
	</script>
</body>
</html>