In Javascript, we can style the element in two different ways. In this tutorial, we are going to style the element in two different ways. Let's get started.
1. Directly adding CSS properties
2. By adding or removing CSS classes
Directly adding CSS properties
Every element in the document has style object which holds all CSS style attribute of the element. We can take any CSS attribute and set it with a valid value in form of a string.
An example directly adding CSS properties
const element = document.getElementById("firstElement");
element.style.color = "green";
element.style.backgroundColor = "yellow";
By adding or removing CSS classes
We can add or remove class value from an element using javascript. The classList property of element provides add() and remove() method using which we can add or remove classes from an element.
An example by adding or removing CSS classes
Adding Class
const element = document.querySelector('h2');
element.classList.add('myClass')
Removing Class
const element = document.querySelector('h2');
element.classList.remove('myClass')
Full Example
0 Comments
If you have any question please ask?