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
- How the Javascript History API Works
- Updating Object Key Values with Javascript
- Sharing Screens with the New Javascript Screen Capture API
- Truthy and Falsy Values in Javascript
- How to fix 'Uncaught SyntaxError: Cannot use import statement outside a module'
- Javascript toLowerCase() - Convert Strings to Lowercase
- Art Generator with Javascript and WebGL
- What is Nullish Coalescing (or ??) in Javascript
- Inserting an Item into an Array at a Specific Index in Javascript
- Javascript Comments