Add/Remove Class in Javascript

Add/Remove Class in Javascript, we will use “classList” function.

When a user clicks on the element, then a class will be added to that element.
Apply your logic using the newly added class, like show hide another div to attract the user.

HTML code

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
     <div id="close-container">
	<button id="my_button"> My Button</button>
    </div>
</body>
</html>

Script code to the toggle class

<script type="text/javascript">
   const myButton = document.getElementById("my_button")
   myButton.addEventListener("click", () => {
   myButton.classList.toggle("hello");
})
</script>

After the first click on “My Button” a “hello” class will be added to the button.
And the second click on that button “hello” class will be removed.

Script code to the add class

<script type="text/javascript">
  const myButton = document.getElementById("my_button")
  myButton.addEventListener("click", () => {
  myButton.classList.add("hello");
})
</script>

After clicking on “My Button” a “hello” class will be added to the button.

Script code to the add class

<script type="text/javascript">
  const myButton = document.getElementById("my_button")
  myButton.addEventListener("click", () => {
  myButton.classList.remove("hello");
})
</script> 

Related Post Detect device in jQuery

Like us on Facebook and Linkedin for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top