Dom Css in JavaScript
? Manipulating CSS with JavaScript (DOM CSS)
JavaScript lets you access and change CSS styles of HTML elements dynamically through the DOM.
1. Accessing and Modifying Inline Styles
You can directly read or change an element’s style using the .style property.
<div id="myDiv" style="color: red;">Hello!</div><script>const elem = document.getElementById("myDiv");// Read styleconsole.log(elem.style.color); // Output: red// Change styleelem.style.color = "blue";elem.style.backgroundColor = "yellow";elem.style.fontSize = "20px";</script>Note:
.styleonly reflects inline styles, not styles applied via CSS files or<style>tags.
2. Reading Computed Styles
To get the actual style applied (including from CSS rules), use window.getComputedStyle().
const elem = document.getElementById("myDiv");const computedStyle = window.getComputedStyle(elem);console.log(computedStyle.color); // e.g. "rgb(0, 0, 255)"console.log(computedStyle.fontSize); // e.g. "16px"3. Adding/Removing CSS Classes
Manipulate element classes with .classList for better style control.
const elem = document.getElementById("myDiv");// Add a classelem.classList.add("highlight");// Remove a classelem.classList.remove("highlight");// Toggle a classelem.classList.toggle("active");// Check if a class existsif (elem.classList.contains("active")) { console.log("Element is active");}4. Example: Change Style on Click
<button id="btn">Change Color</button><div id="box" style="width:100px; height:100px; background:red;"></div><script>const box = document.getElementById("box");const btn = document.getElementById("btn");btn.addEventListener("click", () => { box.style.backgroundColor = "green";});</script>5. CSS Variables (Custom Properties) Manipulation
:root { --main-color: blue;}// Change CSS variable value dynamicallydocument.documentElement.style.setProperty('--main-color', 'orange');Summary
| Method | Usage |
|---|---|
element.style.property | Change inline styles |
window.getComputedStyle() | Read final computed styles |
element.classList | Add/remove/toggle CSS classes |
document.documentElement.style.setProperty | Change CSS variables dynamically |
Want examples on animations with JS and CSS, or how to add styles dynamically with JavaScript?