Javascript

Changing HTML Classes and Attributes in Javascript

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:

html Copy
<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'.

javascript Copy
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:

javascript Copy
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:

javascript Copy
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'

javascript Copy
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.

javascript Copy
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:

javascript Copy
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:

javascript Copy
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:

javascript Copy
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 Sunday, 4 July 2021
Click to Subscribe Subscribed

Subscribe

Subscribe to stay up to date with our latest posts via email. You can opt out at any time.

Not a valid email