How To Add A Class Name To An Element With JavaScript?
Maybe your like
- Home
- Whiteboard
- Online Compilers
- Practice
- Articles
- AI Assistant
- Jobs
- Tools
- Corporate Training
- Courses
- Certifications
- Switch theme
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
To add a class name to an element with JavaScript, the code is as follows −
Example
Live Demo
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> .newStyle { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; width: 100%; padding: 25px; background-color: rgb(147, 80, 255); color: white; font-size: 25px; box-sizing: border-box; text-align: center; } </style> </head> <body> <h1>Adding className with JavaScript Example</h1> <button class="btn">Click here</button> <h2>Click the above button to add className to below div</h2> <div id="sampleDiv"> This is a DIV element. </div> <script> document.querySelector(".btn").addEventListener("click", addClassName); function addClassName() { var element = document.getElementById("sampleDiv"); element.classList.add("newStyle"); } </script> </body> </html>Output
The above code will produce the following output −

On clicking the “Click here” button −

AmitDiwan Updated on: 2020-05-08T13:32:10+05:30 462 Views
Kickstart Your Career
Get certified by completing the course
Get StartedTag » Add Classname To Element Javascript
-
How To Add A Class Name - W3Schools
-
HTML DOM Element ClassName Property - W3Schools
-
Javascript - How To Add A Class To A Given Element? - Stack Overflow
-
JavaScript Adding A Class Name To The Element - GeeksforGeeks
-
assName - Référence Web API | MDN
-
assList - Référence Web API | MDN
-
How To Add A Class To An Element Using JavaScript - Javatpoint
-
How To Add Class Name To The HTML Element Through JavaScript?
-
.addClass() | JQuery API Documentation
-
Add Class To Clicked Element Using JavaScript - Bobbyhadz
-
Add Classname In Javascript Code Example - Code Grepper
-
How To Add A Class To A Given Element In JavaScript
-
Create An Element With Classes Using JavaScript | Bobbyhadz
-
Remove And Add Class Names From Elements Using Pure JavaScript