JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM CSS


JavaScript DOM CSS allows you to control and manipulate the styling of HTML elements dynamically. Using the DOM, JavaScript can change colors, fonts, layouts, visibility, animations, and responsive behavior without reloading the page. This is one of the core reasons modern websites feel interactive and alive rather than static.

In this tutorial, you will learn how JavaScript works with CSS through the DOM, different ways to apply styles, commonly used properties, practical examples, common mistakes, best practices, and real-world use cases.

What Is DOM CSS

DOM CSS refers to using JavaScript to access and modify CSS styles of HTML elements through the DOM. When a web page loads, the browser converts CSS into an object model just like HTML. JavaScript can interact with this model to update styles in real time.

With DOM CSS, you can:

  • Change element styles based on user actions

  • Create themes like dark mode and light mode

  • Apply animations and transitions dynamically

  • Show or hide elements

  • Build responsive behavior without media queries

Why DOM CSS Is Important

DOM CSS is important because it allows developers to:

  • Create interactive user experiences

  • Update UI based on data or user input

  • Reduce page reloads and improve performance

  • Build modern single-page applications

  • Control styling logic directly from JavaScript

Without DOM CSS, websites would rely heavily on static styles and page reloads, limiting interactivity.

Accessing CSS Using JavaScript

JavaScript accesses CSS through the style property of DOM elements.

let heading = document.getElementById("title");
heading.style.color = "blue";

The style property allows you to set inline CSS styles directly on elements.

What is CSS Property Naming

In JavaScript, CSS properties are written in camelCase, not kebab-case.

Examples:

  • background-color becomes backgroundColor

  • font-size becomes fontSize

  • text-align becomes textAlign

let para = document.querySelector("p");
para.style.fontSize = "18px";
para.style.textAlign = "center";

Changing Single CSS Properties

You can change individual CSS properties easily.

let box = document.getElementById("box");
box.style.width = "200px";
box.style.height = "200px";
box.style.backgroundColor = "lightgreen";

Each property is applied immediately to the element.

Changing Multiple CSS Properties

Multiple styles can be applied one by one.

let card = document.querySelector(".card");
card.style.padding = "20px";
card.style.border = "1px solid #ccc";
card.style.borderRadius = "8px";
card.style.boxShadow = "0 4px 10px rgba(0,0,0,0.1)";

This is commonly used when updating UI components dynamically.

Using cssText Property

The cssText property allows you to apply multiple styles at once.

let banner = document.getElementById("banner");
banner.style.cssText = "color: white; background-color: teal; padding: 15px;";

This replaces all existing inline styles, so it should be used carefully.

Reading CSS Values

You can also read inline CSS values using the style property.

let box = document.getElementById("box");
console.log(box.style.backgroundColor);

However, this only reads inline styles, not styles from external stylesheets.

Using getComputedStyle

To read actual computed styles (including external CSS), use getComputedStyle.

let box = document.getElementById("box");
let styles = getComputedStyle(box);
console.log(styles.backgroundColor);
console.log(styles.fontSize);

This is useful when making decisions based on current styling.

Working with CSS Classes

Manipulating classes is often better than changing inline styles.

className Property

let box = document.getElementById("box");
box.className = "active";

This replaces all existing classes, which can be risky.

classList Property

The classList API is safer and more flexible.

box.classList.add("active");
box.classList.remove("active");
box.classList.toggle("active");
box.classList.contains("active");

Using classes keeps styling logic in CSS and behavior in JavaScript.

Practical Examples

Example 1: Dark Mode Toggle

document.getElementById("themeBtn").addEventListener("click", function() {
    document.body.classList.toggle("dark-mode");
});

CSS:

.dark-mode {
    background-color: #121212;
    color: #ffffff;
}

Example 2: Highlight Active Menu Item

let links = document.querySelectorAll(".menu a");

links.forEach(link => {
    link.addEventListener("click", function() {
        links.forEach(item => item.classList.remove("active"));
        this.classList.add("active");
    });
});

Example 3: Show and Hide Elements

let modal = document.getElementById("modal");

function showModal() {
    modal.style.display = "block";
}

function hideModal() {
    modal.style.display = "none";
}

Example 4: Change Style on Scroll

window.addEventListener("scroll", function() {
    let header = document.getElementById("header");
    if (window.scrollY > 50) {
        header.style.backgroundColor = "#333";
    } else {
        header.style.backgroundColor = "transparent";
    }
});

Example 5: Dynamic Progress Bar

let progress = document.getElementById("progress");

function updateProgress(value) {
    progress.style.width = value + "%";
}
updateProgress(70);

Animations and Transitions with DOM CSS

JavaScript can trigger CSS animations and transitions.

let box = document.getElementById("box");
box.style.transition = "transform 0.3s ease";

box.addEventListener("mouseover", function() {
    box.style.transform = "scale(1.1)";
});

box.addEventListener("mouseout", function() {
    box.style.transform = "scale(1)";
});

Using CSS transitions with JavaScript events provides smooth UI effects.

Common Mistakes

  • Using inline styles excessively instead of classes

  • Forgetting camelCase for CSS properties

  • Overwriting existing styles unintentionally

  • Reading styles without using getComputedStyle

  • Mixing styling logic heavily inside JavaScript

Best Practices

  • Prefer class-based styling over inline styles

  • Keep CSS in stylesheets and logic in JavaScript

  • Use classList instead of className

  • Minimize DOM updates for better performance

  • Group style changes to avoid layout thrashing

Real-World Applications

  • Theme switching like dark mode and light mode

  • Interactive navigation menus

  • Modals, popups, and tooltips

  • Responsive UI behavior

  • Dynamic dashboards and admin panels

Summary of JavaScript DOM CSS

JavaScript DOM CSS gives developers full control over how elements look and behave on a web page. By using the style property, classList, and getComputedStyle, JavaScript can dynamically update layouts, colors, visibility, and animations. While inline styles are useful for quick changes, class-based styling is more maintainable and scalable. Understanding DOM CSS is essential for building modern, interactive, and user-friendly web applications.


Practice Questions

  1. Select an element with the class box and change its background color to blue using JavaScript.

  2. Increase the font size of all <p> elements on a page to 18px dynamically.

  3. Select a button and change its text color to white and background color to green using style property.

  4. Add a CSS class highlight to a <div> element when the user clicks a button, and remove it when clicked again.

  5. Use getComputedStyle() to log the current margin and padding of an element with ID container.

  6. Animate a <div> element to move 200px to the right using requestAnimationFrame or setInterval.

  7. Create a hover effect on a <div> using JavaScript by changing its background color and scale when the mouse enters and leaves.

  8. Toggle the hidden class on a paragraph when a button is clicked to show or hide it.

  9. Dynamically change the width and height of a <div> element when the browser window is resized.

  10. Change the border radius of a box element from 0px to 20px smoothly over 0.5 seconds using transition and JavaScript.


Try a Short Quiz.

No quizzes available.


Online Code Editor and Compilor

Write and run code directly in your browser. Live preview for frontend languages.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top