One task, multiple solutions
In Javascript, it is very common to achieve a task in multiple ways.
For example, in the last lesson, on the body
tag, we have replaced the no-js
class with js
class by using the add
and remove
methods of the classList
object.
//Step 1: Select the body element and save it in a variable
let bodyElement = document.querySelector("body");
//Step 2: Remove the "no-js" class from the body element.
bodyElement.classList.remove("no-js");
//Step 3: Add the "js" class
bodyElement.classList.add("js");
But we can also achieve the same result using the replace
method of the classList
object.
//Step 1: Select the body element and save it
let bodyElement = document.querySelector("body");
//Step 2: Replace the "no-js" class with the "js" class.
bodyElement.classList.replace("no-js", "js");
Did you see that?
The replace
method helps us replace one existing class name with another.
It accepts two parameters and replaces the value of the first parameter with the value of the second parameter.
In our case, we are replacing the no-js
class with the js
class.
Simple, right?
💡
Always remember! Javascript language has a lot of inbuilt features. So, often, there will be multiple ways for achieving the same task.We will talk about choosing the best way in a future lesson when we talk about topics like Code Readability and Javascript performance.
Anyway, In the next lesson, we will learn how to change CSS using Javascript.