Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to change font-weight of a text using JavaScript ?
Next article icon

How to change style/class of an element using JavaScript ?

Last Updated : 01 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how we can change the style/class of an element. If you want to build a cool website or app then UI plays an important role. We can change, add or remove any CSS property from an HTML element on the occurrence of any event with the help of JavaScript. There are two common approaches that allow us to achieve this task.

  • style.property
  • Changing the class itself

Approach 1: Changing CSS with the help of the style property:

Syntax:

document.getElementById("id").style.property = new_style

Example: In this example, we have built a PAN number validator. First, we will take the input value and match it with a regex pattern. If it matches then using JavaScript add an inline style on the <p> tag. Otherwise, add a different style on the <p> tag.

HTML




<!DOCTYPE html>
<html lang="en">
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <h2>
        How can the style/class of
        an element be changed?
    </h2>
 
    <b>Validate Pan Number</b>
 
    <input type="text" id="pan" />
    <p></p>
    <button id="submit">Validate</button>
 
    <script>
        const btn = document.getElementById("submit");
        btn.addEventListener("click", function () {
            const pan = document.getElementById("pan").value;
            const para = document.querySelector("p");
 
            let regex = /([A-Z]){5}([0-9]){4}([A-Z]){1}$/;
            if (regex.test(pan.toUpperCase())) {
                para.innerHTML = "Hurrey It's correct";
 
                // Inline style
                para.style.color = "green";
            } else {
                para.innerHTML = "OOps It's wrong!";
 
                // Inline style
                para.style.color = "red";
            }
        });
    </script>
</body>
 
</html>
 
 

Output:

Approach 2: Changing the class itself – We can use two properties that can be used to manipulate the classes.

The classList Property: The classList is a read-only property that returns the CSS class names of an element as a DOMTokenList object. 

Syntax:

document.getElementById("id").classList

You can use the below-mentioned methods to add classes, remove classes, and toggle between different classes respectively.

  • The add() method: It adds one or more classes.
  • The remove() method: It removes one or more classes.
  • The toggle() method: If the class does not exist it adds it and returns true. It removes the class and returns false. The second boolean argument forces the class to be added or removed.

Example: In this example, we are using the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <style>
        .hide {
            display: none;
        }
 
        .blueColor {
            color: blue;
        }
    </style>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
     
    <h2>
        How can the style/class of
        an element be changed?
    </h2>
     
    <h3>Hide and Show the Para</h3>
     
    <p>
        GeeksforGeeks is a computer science portal
        for geeks. This platform has been designed
        for every geek wishing to expand their
        knowledge, share their knowledge, and is
        ready to grab their dream job. GFG have
        millions of articles, live as well
        as online courses, thousands of tutorials
        and much more just for the geek inside you.
    </p>
     
    <button id="hide">Hide</button>
    <button id="show">Show</button>
    <button id="color">Change Color</button>
 
    <script>
        const btn_hide = document.getElementById("hide");
        const btn_show = document.getElementById("show");
        const btn_color = document.getElementById("color");
 
        const para = document.querySelector("p");
        btn_hide.addEventListener("click", function () {
            para.classList.add("hide");
        });
 
        btn_show.addEventListener("click", function () {
            para.classList.remove("hide");
        });
 
        btn_color.addEventListener("click", function () {
            para.classList.toggle("blueColor");
        });
    </script>
</body>
 
</html>
 
 

Output: 

In the above example, we define two manipulation classes “hide” and “toggleColor” which hide an element and change color to blue respectively. When the Hide button is clicked, the hide class is added to the “p” tag which hides it. When the Show button is clicked, it removes the present hide class from the “p” tag. When the Change Color button is clicked once it adds “toggleColor” class to the p tag(which makes the text color blue) and when clicked again it removes the toggleColor class.

The className Property: This property is used to set the current class of the element to the specified class.

Syntax:

document.getElementById("id").className = class

Example: In this example, we are using the className property to change the color of the element.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <style>
        .colorBlue {
            color: blue;
        }
 
        .colorRed {
            color: red;
        }
    </style>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
     
    <h2>
        How can the style/class of
        an element be changed?
    </h2>
     
    <h3>className Example</h3>
     
    <p class="colorBlue">
        GeeksforGeeks is a computer science portal
        for geeks.This platform has been designed
        for every geek wishing to expand their
        knowledge, share their knowledge and is
        ready to grab their dream job. GFG have
        millions of articles, live as well
        as online courses, thousands of tutorials
        and much more just for the geek inside you.
    </p>
     
    <button id="submit">Change Color</button>
 
    <script>
        const btn = document.getElementById("submit");
        const para = document.querySelector("p");
 
        btn.addEventListener("click", function () {
            para.className = "colorRed";
        });
    </script>
</body>
 
</html>
 
 

Output: 

In the above example, the existing ColorBlue class is set to the colorRed class using the className property which changes font color from blue to red.



Next Article
How to change font-weight of a text using JavaScript ?

H

himanshusharma11199
Improve
Article Tags :
  • Geeks Premier League
  • HTML
  • JavaScript
  • Web Technologies
  • Geeks-Premier-League-2022
  • HTML-Questions
  • JavaScript-Properties
  • JavaScript-Questions

Similar Reads

  • How to Change the ID of Element using JavaScript?
    We are given an element and the task is to change the ID of elements using JavaScript. ID is unique for any element and it can be assigned to an element only once. JavaScript provides a method to access this id and also to manipulate the id. Syntax:Selected_element.id = newID;Below are the appraoche
    3 min read
  • How to change style attribute of an element dynamically using JavaScript ?
    Given an HTML document and the task is to change the style properties (CSS Properties) of an element dynamically with the help of JavaScript. Approach: Using element.style PropertyThe element.style property is represented by the CSSStyleDeclaration object, which is returned via the style property. S
    2 min read
  • How to remove a Class name from an Element using JavaScript ?
    Removing a class name from an HTML element using JavaScript is often used to dynamically modify the styling or behavior of an element based on user interactions, events, or other conditions. The operation can be achieved using classList property, that allows you to add, remove, or toggle classes. Sy
    3 min read
  • Change an Element Class with JavaScript
    Here are two different ways to change the element class with JavaScript. 1. Using .className PropertyIn this approach, we are using document.getElementById() method to get access to the element for which we want to change the class name then we use using .className property on that selected element
    2 min read
  • How to change font-weight of a text using JavaScript ?
    In this article, we will set the font-weight of a text dynamically using JavaScript. Ti change the font weight dynamically, we use HTML DOM Style fontWeight property. Syntax: object.style.fontWeight = "value" Property Values: normal: The font weight is the default value.lighter: The font weight is t
    1 min read
  • How to Change the Color of HTML Element in JavaScript?
    Changing the text color of an HTML element in JavaScript improves the user experience. To change the font color of an HTML element using JavaScript, we use the DOM to access and modify its style properties, allowing for dynamic color changes. Syntax:element.style.color = "green";ApproachSelect the T
    2 min read
  • How to Hide an HTML Element by Class using JavaScript?
    To hide an HTML element by class using JavaScript, the CSS display property can be manipulated. Below are the approaches to hide an HTML element by class: Table of Content Using getElementsByClassName() selectorUsing querySelectorAll() selectorApproach 1: Using getElementsByClassName() selectorIn th
    3 min read
  • How to Toggle an Element Class in JavaScript ?
    In JavaScript, toggling an element class refers to the process of dynamically adding or removing a CSS class from an HTML element. This allows developers to easily change an element's appearance or behavior in response to user actions, such as clicks or events. These are the following methods for to
    2 min read
  • How to Add an Active Class to the Current Element Using JavaScript?
    We can make use of JavaScript to add an active class to the current element by directly manipulating its class list. This involves identifying the element that triggered the interaction, removing the active class from any previously active elements, and then applying the active class to the current
    3 min read
  • How to set the color of an element border with JavaScript ?
    In this article, we will see how to set the color of an element's border with JavaScript. To set the color of an element's border with JavaScript, we can use the element's style property. Method 1: First, we will create a text element and then apply some CSS styles including the border color of the
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences