JavaScript

coding learning websites codepractice

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


What is DOM CSS?

DOM CSS refers to the way JavaScript interacts with CSS styles of HTML elements on a webpage. Through DOM CSS, you can read, modify, add, or remove styles dynamically, giving your page interactivity and visual responsiveness.

While HTML defines the structure, and CSS defines the presentation, DOM CSS allows JavaScript to bridge the two by controlling styles programmatically.

Why DOM CSS is Important

Using DOM CSS, you can:

  • Change visual appearance dynamically based on user interaction.

  • Apply animations, hover effects, and themes programmatically.

  • Highlight form errors or important elements.

  • Respond to user actions like clicks, mouseover, scrolling, and input.

  • Create interactive UI components without refreshing the page.

DOM CSS is essential for modern web applications where the interface must react to user behavior.

Accessing CSS Styles

Using style Property

Every DOM element has a style property representing inline CSS styles.

let heading = document.getElementById("main-heading");
heading.style.color = "red";
heading.style.fontSize = "30px";
heading.style.fontWeight = "bold";

Note: style only accesses inline styles directly set via JavaScript or HTML. It does not reflect styles applied via external or internal CSS files.

Using getComputedStyle()

To read all styles, including those from CSS files, use window.getComputedStyle():

let heading = document.getElementById("main-heading");
let styles = window.getComputedStyle(heading);

console.log("Color:", styles.color);
console.log("Font Size:", styles.fontSize);

getComputedStyle is useful for calculations and dynamic adjustments based on existing styles.

Modifying Styles Dynamically

Changing Single Styles

let box = document.querySelector(".box");
box.style.backgroundColor = "#f0f0f0";
box.style.border = "2px solid blue";
box.style.padding = "10px";

Changing Multiple Styles

Object.assign(box.style, {
    color: "white",
    fontSize: "18px",
    textAlign: "center"
});

Using Object.assign is more readable when applying multiple styles at once.

Working with Classes

Instead of modifying inline styles, it’s often better to add or remove CSS classes, which can be predefined in a stylesheet.

let heading = document.getElementById("main-heading");

heading.classList.add("highlight");   // Add class
heading.classList.remove("highlight"); // Remove class
heading.classList.toggle("highlight"); // Toggle class
heading.classList.contains("highlight"); // Check if class exists

Using classes is preferred for maintainability and consistency across the site.

Animations with DOM CSS

Using transition for Smooth Effects

let box = document.querySelector(".box");
box.style.transition = "all 0.5s ease";

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

box.addEventListener("mouseout", () => {
    box.style.backgroundColor = "red";
    box.style.transform = "scale(1)";
});
  • transition ensures changes happen smoothly over time.

  • Hover effects or mouse events can trigger dynamic animations.

Using setInterval or requestAnimationFrame for Custom Animations

let box = document.querySelector(".box");
let position = 0;

function moveBox() {
    if (position < 200) {
        position++;
        box.style.left = position + "px";
        requestAnimationFrame(moveBox);
    }
}

moveBox();

You can animate positions, sizes, or other CSS properties dynamically.

Responsive Design with JavaScript

You can adjust styles based on screen size or events:

window.addEventListener("resize", () => {
    let width = window.innerWidth;
    let box = document.querySelector(".box");

    if (width < 600) {
        box.style.backgroundColor = "pink";
    } else {
        box.style.backgroundColor = "lightgreen";
    }
});

DOM CSS allows real-time adjustments to make your page responsive.

Practical Example

<div class="box" style="width:100px; height:100px; background:red; position:relative;"></div>
<button id="changeBtn">Change Style</button>
let box = document.querySelector(".box");
document.getElementById("changeBtn").addEventListener("click", () => {
    // Change inline styles dynamically
    box.style.backgroundColor = "blue";
    box.style.width = "150px";
    box.style.height = "150px";
    box.style.borderRadius = "20px";
});

When the button is clicked, the box’s appearance changes instantly without page reload.

Best Practices

  • Prefer CSS classes over inline styles for maintainability.

  • Use getComputedStyle() to read existing styles accurately.

  • Always consider performance when updating multiple elements in loops.

  • Use transitions or animations for smooth visual changes.

  • Combine media queries with JavaScript for responsive behavior.

Summary of the Tutorial

DOM CSS allows you to access, modify, and animate styles dynamically using JavaScript. Key methods and properties include:

  • element.style – Access or set inline styles.

  • getComputedStyle() – Read computed styles, including external CSS.

  • classList – Add, remove, toggle, or check CSS classes.

  • Transitions and animations – Animate style changes smoothly.

  • Responsive adjustments – Change styles dynamically based on user actions or screen size.

Mastering DOM CSS is essential for creating interactive, visually appealing, and responsive web pages.


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.


JavaScript

online coding class codepractice

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