ArticleZip > Use Vanilla Javascript To Add Remove Class To A Different Element After Clicking On Another One

Use Vanilla Javascript To Add Remove Class To A Different Element After Clicking On Another One

When it comes to web development, using Vanilla JavaScript can be a powerful tool in your arsenal. One common task web developers face is adding or removing a class from one element after clicking on another. This simple yet effective technique can enhance user interactions and overall site functionality. In this article, we'll walk through how to achieve this using Vanilla JavaScript.

To start off, let's understand the basic concept behind adding or removing a class from an element. A class in CSS is a way to apply styling to HTML elements. By adding or removing a class dynamically using JavaScript, we can change the appearance or behavior of an element on the webpage.

Firstly, we need to identify the elements we want to work with in our HTML code. Let's say we have two elements - element1 and element2. We want to add a class to element2 when element1 is clicked. Here's a simple example of the HTML structure:

Html

<div id="element1">Click me!</div>
<div id="element2">Change my style</div>

Next, we'll write the JavaScript code to accomplish this functionality. We can achieve this by targeting the elements and adding an event listener to element1 for the click event. When the click event occurs, we will add the desired class to element2. Here's the JavaScript code snippet:

Javascript

const element1 = document.getElementById('element1');
const element2 = document.getElementById('element2');

element1.addEventListener('click', function() {
    element2.classList.toggle('newClass');
});

In the code snippet above, we first retrieve references to element1 and element2 using `document.getElementById`. Then, we add an event listener to element1 for the 'click' event. When element1 is clicked, the anonymous function inside the event listener is triggered. Within this function, we use `classList.toggle('newClass')` to toggle the class 'newClass' on and off for element2.

Now, let's explain `classList.toggle('newClass')` in more detail. The `classList` property returns the class attribute of an element as a DOMTokenList object. By using `toggle('newClass')`, we can add the class 'newClass' to element2 if it is not present, and remove it if it is already present.

By following these steps, you can easily add or remove a class from a different element after clicking on another one using Vanilla JavaScript. This technique can be useful for creating interactive elements, building dynamic menus, or implementing a wide range of user interface improvements on your website.

In conclusion, mastering the basics of manipulating HTML elements with Vanilla JavaScript opens up a world of possibilities for web development. Experiment with different scenarios and explore the endless ways you can enhance the user experience on your websites. Happy coding!