Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Css in JavaScript

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: .style only 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

MethodUsage
element.style.propertyChange inline styles
window.getComputedStyle()Read final computed styles
element.classListAdd/remove/toggle CSS classes
document.documentElement.style.setPropertyChange CSS variables dynamically

Want examples on animations with JS and CSS, or how to add styles dynamically with JavaScript?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql