0
0
JavascriptHow-ToBeginner · 3 min read

How to Change Style in JavaScript: Simple Guide

You can change the style of an HTML element in JavaScript by accessing its style property and setting CSS properties as JavaScript properties, like element.style.color = 'red'. This directly modifies the inline style of the element on the page.
📐

Syntax

To change the style of an element, first select it using methods like document.getElementById or document.querySelector. Then, use the style property to set CSS properties in camelCase format.

  • element.style.propertyName = 'value'; — sets a CSS property.
  • Property names use camelCase instead of hyphens (e.g., backgroundColor instead of background-color).
javascript
const element = document.getElementById('myElement');
element.style.color = 'blue';
element.style.backgroundColor = 'yellow';
💻

Example

This example changes the text color and background color of a paragraph when the page loads.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Change Style Example</title>
</head>
<body>
  <p id="text">Hello, watch my style change!</p>
  <script>
    const text = document.getElementById('text');
    text.style.color = 'white';
    text.style.backgroundColor = 'green';
    text.style.fontSize = '20px';
  </script>
</body>
</html>
Output
A paragraph with white text on a green background and font size 20px.
⚠️

Common Pitfalls

Common mistakes when changing styles in JavaScript include:

  • Using CSS property names with hyphens instead of camelCase (e.g., element.style.background-color is invalid).
  • Trying to set styles on null if the element is not found.
  • Expecting changes to affect CSS classes instead of inline styles.
javascript
const el = document.getElementById('missing');
// Wrong: will cause error if el is null
// el.style.background-color = 'red';

// Correct:
if(el) {
  el.style.backgroundColor = 'red';
}
📊

Quick Reference

ActionSyntax Example
Select element by IDconst el = document.getElementById('id');
Change text colorel.style.color = 'blue';
Change background colorel.style.backgroundColor = 'yellow';
Change font sizeel.style.fontSize = '16px';
Check element existsif(el) { /* safe to change style */ }

Key Takeaways

Use the element's style property with camelCase CSS names to change styles.
Always check the element exists before changing its style to avoid errors.
Changing style via JavaScript modifies inline styles directly on the element.
CSS property names with hyphens must be converted to camelCase in JavaScript.
Use document selectors like getElementById or querySelector to access elements.