Clean β’ Professional
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.
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;";
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");
}
classList avoids repetitive inline styling.