Add Remove Class Javascript Codepen

Add Remove Class Javascript Codepen

4 min read Jun 20, 2024
Add Remove Class Javascript Codepen

Adding and Removing Classes with JavaScript: A CodePen Example

This article will guide you through the process of adding and removing classes using JavaScript, a fundamental skill for building dynamic web applications.

Setting up the HTML:

First, let's create a simple HTML structure:

    Add/Remove Class Example


This is a paragraph.

In this HTML, we have a button with the ID "myButton" and a paragraph with the ID "myParagraph." We also define a CSS class called "active" that will change the background color and font weight of an element when applied.

JavaScript Code:

Now, let's write the JavaScript code that will add and remove the "active" class:

const button = document.getElementById('myButton');
const paragraph = document.getElementById('myParagraph');

button.addEventListener('click', () => {
  if (paragraph.classList.contains('active')) {
  } else {

Here's a breakdown of the code:

  • const button = document.getElementById('myButton');: This line selects the button element with the ID "myButton" and stores it in the button variable.
  • const paragraph = document.getElementById('myParagraph');: This line selects the paragraph element with the ID "myParagraph" and stores it in the paragraph variable.
  • button.addEventListener('click', () => { ... });: This adds a click event listener to the button. When the button is clicked, the code inside the curly braces will execute.
  • if (paragraph.classList.contains('active')) { ... } else { ... }: This checks if the paragraph element already has the "active" class. If it does, it removes the class using classList.remove('active'). Otherwise, it adds the class using classList.add('active').

Testing the Code:

You can test the code by copying it into a CodePen project or by saving it as an HTML file and opening it in your web browser. When you click the button, the paragraph should change its appearance based on whether it has the "active" class or not.

Important Notes:

  • classList: The classList property is a powerful way to manage classes on HTML elements. It allows you to add, remove, and check for the existence of classes.
  • addEventListener: This is a fundamental JavaScript feature for adding event listeners to elements, enabling interaction with your website.

This simple example demonstrates the core principles of adding and removing classes with JavaScript. This technique can be extended to create more complex interactions, animations, and dynamic UI elements on your web pages.