Change Style of HTML Element using JavaScript

In this tutorial, we shall learn to change style of HTML Element programmatically using HTMLElement.style.

JavaScript can update an element’s inline CSS through the style property. This is useful when a style has to change after a user action, form validation, animation state, theme choice, or any other browser-side condition.

HTMLElement.style syntax for changing inline CSS with JavaScript

The syntax to change style of a HTML element dynamically using JavaScript is

</>
Copy
HTMLElement.style="styling_data"

The value assigned to HTMLElement.style is inline CSS. You can also update individual CSS properties on the style object. This second form is often easier to read when only one or two properties have to be changed.

</>
Copy
element.style.propertyName = "value";

For CSS property names that contain hyphens, JavaScript usually uses camel case. For example, background-color becomes backgroundColor, and font-size becomes fontSize.

</>
Copy
const box = document.getElementById("box");

box.style.backgroundColor = "#f5f5f5";
box.style.fontSize = "18px";
box.style.padding = "12px";

Change style of an HTML element via getElementById()

A simple code snippet to change the style of an element whose id is message is

</>
Copy
document.getElementById("message").style="color:#f00;padding:5px;"

Any styling properties supported by the HTML Element can be supplied in the assigned value, just like inline style CSS.

In the following example, we shall get reference to an HTML DOM Element using document.getElementById() method, and change its style value.

index.html

</>
Copy
<!doctype html>
<html>
<body>
    <h1>JavaScript HTMLElement.style Example</h1>
    <p id="message">This is a paragraph.</p>
    <script>
        <!-- your JavaScript goes here -->
        var messageElement = document.getElementById("message");
        <!-- try changing the styles and run -->
        messageElement.style="color:#090;border:1px solid #aaa;text-align:center;";
    </script>
</body>
</html>

The paragraph is selected by its id, and the JavaScript statement writes inline CSS to the element. After the script runs, the text color, border, and alignment are applied directly to the paragraph.

Change one CSS property at a time with HTMLElement.style

Instead of replacing the complete inline style text, you can change individual properties. This is safer when the element already has inline styles that you do not want to overwrite.

</>
Copy
<p id="status">Status message</p>

<script>
    const statusElement = document.getElementById("status");

    statusElement.style.color = "green";
    statusElement.style.border = "1px solid #aaa";
    statusElement.style.textAlign = "center";
</script>

In the example above, each CSS property is updated separately. This keeps the code clear and avoids replacing unrelated inline style values by accident.

Use cssText when replacing the complete inline style string

The cssText property is another way to assign a full inline CSS string. It makes the intention clearer when you want to replace the element’s entire inline style declaration.

</>
Copy
<div id="notice">Payment is pending.</div>

<script>
    const notice = document.getElementById("notice");

    notice.style.cssText = "color:#8a4b00;background-color:#fff4d6;padding:10px;";
</script>

Use cssText carefully because it replaces the complete inline style value. If the element already has inline CSS, that earlier inline CSS can be removed unless you include it in the new string.

Change hyphenated CSS properties with setProperty()

For normal CSS properties, camel case works well. For custom properties such as CSS variables, or when you want to use the original CSS property name with hyphens, use style.setProperty().

</>
Copy
<div id="card">Product card</div>

<script>
    const card = document.getElementById("card");

    card.style.setProperty("background-color", "#eef6ff");
    card.style.setProperty("--card-gap", "16px");
</script>

The first argument is the CSS property name, and the second argument is the value. This is especially useful when the property name cannot be written naturally as a JavaScript property.

Change style of multiple HTML elements via getElementsByClassName()

In the following example, we shall get reference to an HTML DOM Elements using document.getElementsByClassName() method, and change their style value,

index.html

</>
Copy
<!doctype html>
<html>
<body>
    <h1>JavaScript HTMLElement.style Example</h1>
    <p class="message">This is a paragraph.</p>
    <p class="message">This is another paragraph.</p>
    <script>
        <!-- your JavaScript goes here -->
        var x = document.getElementsByClassName("message");
        <!-- try changing the styles and run -->
        for (i = 0; i < x.length; i++) {
            x[i].style = "padding:20px;border:1px solid #bbb;";
        } 
    </script>
</body>
</html>

getElementsByClassName() returns a collection, so the style has to be applied inside a loop. The same idea can be used with querySelectorAll() when you want to select elements using a CSS selector.

</>
Copy
<p class="message">First message</p>
<p class="message">Second message</p>

<script>
    const messages = document.querySelectorAll(".message");

    messages.forEach(function (message) {
        message.style.padding = "20px";
        message.style.border = "1px solid #bbb";
    });
</script>

When classList is better than changing many style properties

For a one-time style change, HTMLElement.style is direct. For a reusable visual state, adding or removing a CSS class is usually easier to maintain. It keeps the styling in CSS and keeps JavaScript focused on behavior.

</>
Copy
<style>
    .error-message {
        color: #b00020;
        border: 1px solid #b00020;
        padding: 10px;
    }
</style>

<p id="form-error">Please enter a valid email address.</p>

<script>
    const error = document.getElementById("form-error");

    error.classList.add("error-message");
</script>

This approach is helpful when the same style is used in more than one place, when the style has many properties, or when designers need to update CSS without editing JavaScript.

Common mistakes when changing CSS styles with JavaScript

  • Using CSS property names with hyphens as dot properties: write element.style.backgroundColor, not element.style.background-color.
  • Forgetting units: many CSS values need units, such as "20px", "1rem", or "50%".
  • Trying to style a missing element: check that getElementById() did not return null before applying styles.
  • Replacing all inline styles unintentionally: assigning a full style string or cssText can overwrite existing inline CSS.
  • Using inline style for large design changes: prefer classList when the style represents a reusable state such as active, hidden, selected, or error.

FAQs on changing HTML element style using JavaScript

1. How do I change the color of an HTML element using JavaScript?

Select the element and assign a value to its style.color property. For example, document.getElementById("message").style.color = "red";.

2. How do I change background-color with JavaScript?

Use the camel-case property name backgroundColor. For example, element.style.backgroundColor = "#f5f5f5";. You can also use element.style.setProperty("background-color", "#f5f5f5");.

3. Should I use style or classList to change CSS with JavaScript?

Use style for small dynamic changes such as setting a computed width, color, or position. Use classList when the change represents a reusable CSS state with several style rules.

4. Why is my JavaScript style change not working?

Check that the selected element exists, the property name is written correctly in JavaScript, the value includes required units, and another CSS rule with higher priority is not overriding the visible result.

5. Can JavaScript change the style of all elements with the same class?

Yes. Select the elements with getElementsByClassName() or querySelectorAll(), then loop through the returned collection and apply the style to each element.

Editorial QA checklist for this JavaScript style tutorial

  • Confirms that HTMLElement.style changes inline CSS on a selected element.
  • Shows both full inline style assignment and individual property assignment.
  • Explains camel-case JavaScript property names such as backgroundColor and fontSize.
  • Includes a multi-element example using a loop over class-matched elements.
  • Clarifies when classList is easier to maintain than many direct style changes.

Summary of changing HTML element style with JavaScript

JavaScript can change the style of an HTML element by selecting the element and updating its style property. Use individual style properties for small changes, cssText when replacing the full inline style is intentional, setProperty() for hyphenated names and CSS variables, and classList for reusable design states.

In this JavaScript Tutorial, we have learnt to change style of HTML Element dynamically using HTMLElement.style, with the help of Try Online Examples.