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');
More Tips and Tricks for Javascript
- The Many Quirks of Javascript Dates
- Resolving HTTP Cannot set headers after they are sent to the client in Node.JS
- Detecting Device Orientation with Javascript
- Instagram Style Video Preload Static Effect
- Asynchronous Operations in Javascript
- Using an Array as Function Parameter in JavaScript
- The Complete Guide to JavaScript Set Type
- Making your own Email Subscription Service with Node.JS
- Check if an Object Contains all Keys in Array in Javascript
- Javascript loops: for vs forEach vs for.. in vs for.. of