Part of Series: Javascript Handbook
Javascript

Changing HTML Classes and Attributes in Javascript

📣 Sponsor

HTML elements typically have classes and attributes. For example, the below code has a class called active and an attribute called data-settings which is set to true:

<div class="active" data-settings="true"> This is my div </div>

We can alter these in Javascript, which means we can change HTML based on conditions we set up in our code.

Adding and Removing Classes

To start, we need to select the HTML elements we want to change. Let's assume for our examples, that we have an element with the id 'my-id'.

const myElement = document.getElementById('my-id');

Adding Classes

All class changes take place through classList. So to add a new class 'some-new-class' to our element, we would do the following:

const myElement = document.getElementById('my-id'); myElement.classList.add('some-new-class');

Removing Classes

Similarly, if we want to remove a class using Javascript, we do the following:

const myElement = document.getElementById('my-id'); myElement.classList.remove('some-new-class');

Replacing Classes

We can also replace one class with another. The below will replace 'some-new-class' with 'another-class'

const myElement = document.getElementById('my-id'); myElement.classList.replace('some-new-class', 'another-class');

Toggling a Class

Sometimes we don't know if a class is on an element or not. As such, we can use toggle to add a class if it is there, and remove it if it is not.

const myElement = document.getElementById('my-id'); myElement.classList.toggle('active-class');

Checking if an element has a class

We can also check if our element has a class, using contains:

const myElement = document.getElementById('my-id'); if(myElement.classList.contains('active-class')) { // Do something if the element has a class 'active-class' }

Changing Attributes in Javascript

To change HTML attributes, we can use setAttribute:

const myElement = document.getElementById('my-id'); // Sets myElement's data-attribute attribute to true myElement.setAttribute('data-attribute', true);

Retrieving Attribute Values

We can also retrieve the value of attributes, using getAttribute. If the attribute doesn't exist, it will return null:

const myElement = document.getElementById('my-id'); // This will get the current value to myElement's attribute called 'data-attribute'. let dataAttribute = myElement.getAttribute('data-attribute');
Last Updated 1625395894695

More Tips and Tricks for Javascript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email