J

JavaScript Handbook

Clean • Professional

DOM CSS in JavaScript

1 minute

DOM CSS

In the HTML DOM, JavaScript can manipulate the CSS styles of HTML elements dynamically, allowing you to change the appearance of a webpage in real-time. This includes modifying inline styles, toggling classes, and applying multiple style changes efficiently. Using the DOM for CSS makes web pages interactive and responsive without requiring a full page reload.

Key Methods to Manipulate CSS

1. style Property

The style property allows direct access to an element's inline styles. You can get or set individual CSS properties.

Example:

const element = document.getElementById("myDiv");

// Change background color
element.style.backgroundColor = "lightblue";

// Set multiple styles
element.style.cssText = "color: white; font-size: 20px;";

2. classList Property

The classList property provides methods to manage CSS classes efficiently.

Common Methods:

  • add(className): Adds a class.
  • remove(className): Removes a class.
  • toggle(className): Adds the class if not present, removes if present.
  • contains(className): Checks if the element has a specific class.

Example:

const box = document.querySelector(".box");

// Add a class
box.classList.add("highlight");

// Remove a class
box.classList.remove("hidden");

// Toggle a class
box.classList.toggle("active");

// Check if class exists
if(box.classList.contains("highlight")) {
    console.log("Box is highlighted");
}

Advantages of Using DOM CSS Manipulation

  1. Dynamic Styling: Change styles instantly in response to user actions.
  2. Interactive UI: Add hover effects, animations, and visual feedback.
  3. Conditional Styling: Apply different styles based on conditions or events.
  4. Cleaner HTML: Using classes via classList avoids repetitive inline styling.

Article 0 of 0