Skip to main content

Javascript and CSS

Updating CSS on HTML elements using JavaScript is a common practice, especially in interactive web applications.

Using style Property

You can directly modify the inline style of an HTML element using JavaScript's style property.

const element = document.getElementById("myElement");
element.style.color = "red";
element.style.fontSize = "24px";

Using classList

The classList property allows you to add, remove, or toggle CSS classes on an element.

// Add a class
element.classList.add("new-class");

// Remove a class
element.classList.remove("old-class");

// Toggle a class
element.classList.toggle("toggle-class");

Using setAttribute and removeAttribute

You can use these methods to set or remove a style attribute.

// Set multiple styles
element.setAttribute("style", "color: red; font-size: 24px;");

// Remove style attribute
element.removeAttribute("style");

Using cssText

You can set multiple inline styles at once using cssText.

element.style.cssText = "color: red; font-size: 24px;";

Modifying Stylesheets

You can also dynamically create or modify stylesheets.

// Create a new stylesheet
const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = '.newClass { color: red; }';
document.head.appendChild(styleSheet);

// Modify an existing stylesheet
document.styleSheets[0].insertRule('.newClass { color: red; }', 0);

Best Practices

  1. Separation of Concerns: Whenever possible, try to keep styles in CSS files and use JavaScript to toggle class names rather than directly setting styles.

  2. Performance: Minimize DOM manipulations by batching changes or using Document Fragments.

  3. Readability: Use descriptive variable and class names to make the code more maintainable.

  4. Compatibility: Ensure that the methods you use are supported in the target browsers.

  5. Accessibility: Make sure that any JavaScript-based style changes do not hinder accessibility.

Examples

Change Color on Button Click

HTML:

<button id="changeColorBtn">Change Color</button>
<div id="colorBox"></div>

CSS:

#colorBox {
width: 100px;
height: 100px;
background-color: blue;
}

JavaScript:

document.getElementById("changeColorBtn").addEventListener("click", function() {
const colorBox = document.getElementById("colorBox");
colorBox.style.backgroundColor = "red";
});