Adding a class name to an element allows the user to assign a specific set of styling rules to that element. This can be used to create a more visually appealing page, as well as to add additional functionality. By assigning a class name to an element, the user can quickly and easily change the look and feel of the page in real time.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
Register for Webinar
How you can accelerate your learnings
1. Create a variable and set it equal to the element you want to add a class name to.
2. Create a variable and set it equal to the class name you want to add to the element.
3. Use the element's classList.add() method to add the class name to the element.
4. Return the element with the added class name.
// Sample Code
let element = document.getElementById("mydiv");
let className = "newclass";