The Wayback Machine - https://web.archive.org/web/20240919221929/https://www.geeksforgeeks.org/how-to-change-style-class-of-an-element-using-javascript/
Open In App

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

Last Updated : 01 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

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. Select the element whose style properties need to b
2 min read
How to change the ID of element using JavaScript ?
In this article, we will learn how 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;There are two approaches that are discussed below: Table of Content Using the
3 min read
How to change the src attribute of an img element in JavaScript / jQuery ?
The task is to change the src attribute of the &lt;img&gt; element by using JQuery and JavaScript. jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets
3 min read
How to get/change the HTML with DOM element in JavaScript ?
In order to get/access the HTML for a DOM element in JavaScript, the first step is to identify the element base on its id, name, or its tag name. Then, we can use inner.HTML or outer.HTML to get the HTML. Using the getElementById() method: This method gets/identifies the DOM elements using its ID and returns the element. Example: In this example, w
3 min read
Change the Border of HTML Element in JavaScript
In this article, we will see how to change the Border of HTML element using JavaSCript. To change the border of an element, first, we select the element, and then use HTML DOM border style property to change the border. The CSS border properties are given below: border-style: The border-style In JavaScript, the color property of an element is used
3 min read
Change an Element Class with JavaScript
The class name is used as a selector in HTML which helps to give some value to the element attributes. The document.getElementById() method is used to return the element in the document with the "id" attribute and the "className" attribute can be used to change/append the class of the element. Syntax: document.getElementById('myElement').className
2 min read
How to Change the Color of HTML Element in JavaScript ?
Changing the color of an HTML element dynamically in JavaScript improves the user experience. To change the color of an HTML element with JavaScript, we use the DOM to access and modify its style properties, allowing for dynamic color changes. In this article, we will see how to change the HTML Element's color using Javascript, along with understan
2 min read
JavaScript Change the Text of a Span Element
In JavaScript, changing the text of a span element allows you to dynamically update content on a webpage. This is done by selecting the span using methods like getElementById or querySelector and modifying its innerText or textContent property. This technique is widely used for interactive web features. There are two properties used to change the c
2 min read
How to change the element id using jQuery ?
The jQuery methods are used to change the element ID which are described below: jQuery attr() Method: This method set/return attributes and values of the selected elements. If this method is used to return the attribute value, it returns the value of first selected element. If this method is used to set attribute values, it sets one or more than on
3 min read
How to change an HTML element name using jQuery ?
Given an HTML document and the task is to replace an HTML element by another element. For example: we can change an element &lt;b&gt; with &lt;h1&gt; element without changing any other property.Approach: Select the HTML element which need to be change.Copy all attributes of previous element in an object.Replace the previous element by new element.
2 min read
How to change an element color based on value of the color picker value using onclick?
We can define color picker by input type="color". It provides a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format. Only colors without alpha channels are allowed. Though CSS colors have more formats, e.g. color names, func
2 min read
How to change opacity of every data element on hover in a table using CSS ?
There is a Table made by using HTML in which data elements are set to a low opacity. The task is to change the opacity of a particular element when user hover over data elements. To make a table look better, we will use gradient colors to set backgrounds of the table data elements. In this approach, we will be using the opacity property of CSS to c
2 min read
How to change color of tooltip element using Bootstrap ?
In this article, we will see how to change the color of the tooltip element using Bootstrap. A Tooltip is used to provide interactive textual hints to the user about the element when the mouse pointer moves over. The tooltip is quite useful for displaying the description of different elements on the webpage. Now, let’s learn how to create a tooltip
2 min read
How to change the color of horizontal line (hr element) using CSS ?
The HTML &lt;hr&gt; tag is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections. The color of the &lt;hr&gt; tag can be set by using the background-color property in CSS. Example 1: In this example, the CSS within the &lt;style&gt; section customizes the &lt;hr&gt; element with a red backgroun
2 min read
Using the useRef hook to change an element's style in React
In this article, we will learn how to change an element's style using the useRef hook. UseRef() allows us to create a reference to a DOM element and keep track of variables without causing re-renders.  Prerequisites:NPM &amp; Node JSReact JSReact useRef HookTo use a ref to change an element's style in React:We will import the useRef hook to access
3 min read
How to change font style on element using Bootstrap 5?
Bootstrap enables changing font styles by applying predefined classes like .fw-bold for bold, .fst-italic for italic, etc., directly to HTML elements. This ensures consistent and responsive typography across web applications without needing custom CSS. There are a few Bootstrap Built-in Classes for adding the styling to the font, which are describe
2 min read
How to change the shape of a textarea using JavaScript ?
In General, Textarea will be in the form of rectangular or square shapes, but here we will deal with Unusual shapes of textarea which means this textarea will not be regular shapes but editable. Method 1: In the first method, let's see the irregular editable textarea created using CSS-shapes and content editable attribute when it is true. Example:
2 min read
How to change text color depending on background color using JavaScript?
The task is to set the foreground color based on the background color so that it will become visible. Here few of the important techniques are discussed. We are going to use JavaScript. Approach: First, select the random Background color(by selecting random RGB values) or a specific one.Use the YIQ formula to get the YIQ value.Depending on the YIQ
3 min read
How to disable scroll to change number in &lt;input type="number"&gt; field using JavaScript/jQuery?
Given an HTML document containing &lt;input type = "number"&gt; attribute and the task is to disable the mouse scroll wheel to change the number value using JavaScript/jQuery. Approach: Select the element.Add an event to that element which will call a function when scrolling starts.Make the element disabled on scrolling.Example 1: This example impl
2 min read
How to change the value of a global variable inside of a function using JavaScript ?
Pre-requisite: Global and Local variables in JavaScript Local Scope: Variables that are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed. Global Scope: Global variables can be accessed from inside and outside the function. They are delete
2 min read
How to change the href value of a tag after click on button using JavaScript ?
JavaScript is a high-level, interpreted, dynamically typed, and client-side scripting language. HTML is used to create static web pages. JavaScript enables interactive web pages when used along with HTML and CSS. Document Object Manipulation (DOM) is a programming interface for HTML and XML documents. DOM acts as an interface between JavaScript and
4 min read
How to Change Background Color of a Div on Mouse Move Over using JavaScript ?
The background color of the div box can be easily changed using HTML, CSS, and Javascript. We will use the querySelector() and addEventListener() methods to select the element and then apply some math logic to change its background color. The below sections will guide you on how to create the effect. HTML Code: In this section, we will create a bas
2 min read
How to change background color according to the mouse location using JavaScript ?
The background color can be changed according to the cursor position using the DOM (Document Object Model). In this article, we use the position of the cursor to set the value of the background. Approach: The approach is to use DOM manipulation to change the background according to the cursor position at a particular time. HTML Code: In this sectio
2 min read
How to change font style using drop-down list in JavaScript ?
To change or set a font style for certain text, the fontFamily CSS property needs to be changed. The fontFamily property sets or returns a list of font-family names for text in an element. Syntax: object.style.fontFamily = "font" To change the font style by option dropdown: The font values can be passed in option tags using option value. Syntax:
2 min read
How to change Input box borders after filling the box using JavaScript ?
In this article, we will change the input border after filling in the text on the input text field. The onchange event attribute works when the value of the element changes and selects the new value from the list. Approach: Whenever the input value is changed with some value by the user, the onchange event attribute is triggered. After the event is
2 min read
How to change the width of an iframe to 100% using JavaScript ?
In this article, we are given an HTML document containing an &lt;iframe&gt; element and the task is to change the width of the &lt;iframe&gt; element to 100% with the help of JavaScript. There are two methods to change the width of the iframe which are discussed below: Method 1: This method uses the id attribute of iframe with width property to cha
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 the lighter than normal.bold: The font weight is bo
1 min read
How to change a button text on click using localStorage in Javascript ?
In this article, we will learn how to change a button text using Javascript localStorage when we click on the button achieved by adding HTML onclick event listener. Approach: HTML DOM Window localStorage allows us to store key-value pairs in our browser using an object. The name of the key should be unique and key-value pairs always be stored in st
3 min read
How to Change the Margin of Paragraph using JavaScript ?
The CSS Margin property is used to give space around elements. It is completely transparent and has no background color. It clears up space around the component. Using separate properties, you can independently change the top, bottom, left, and right margins. In this article, we'll see how to change the margin of the paragraph using javascript. CSS
4 min read
How to Change CSS Properties using JavaScript EventListner Methods ?
In this article, we will be using JavaScript to update the web page's CSS styling by taking input from the user. Generally, we have seen a few webpages update the various styling properties dynamically by taking the user input that enhances the user interaction with the webpage, along with improving the overall user experience by engaging the users
3 min read