How to Alter a CSS Stylesheet Using JavaScript? (Not the Style of an Object, But the Stylesheet Itself)

Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)

As of 2011

Yes you can, but you will be facing cross-browser compatibility issues:

http://www.quirksmode.org/dom/changess.html

As of 2016

Browser support has improved a lot (every browser is supported, including IE9+).

  • The insertRule() method allows dynamic addition of rules to a stylesheet.

  • With deleteRule(), you can remove existing rules from a stylesheet.

  • Rules within a stylesheet can be accessed via the cssRules attributes of a stylesheet.

Changing inline style vs. changing external stylesheet style using JS

When temporarily accessing or modifying an element's style using Javascript, there is no difference involved in whether that style was defined inline or in css - you will get the style that is applied by precedence and Javascript changes will override any declared style.

However, general best practice is to have a separate stylesheet (or maybe several if you intend to have conditional stylesheets for IE9 and below, or to split up lots of styles into manageable chunks)

This method is less complicated when it comes to debugging and changing styles in real time.

With external stylesheets you can change the entire site in seconds by dropping a new .css file in place. You can't do that with inline styles.

How to change external CSS on the fly

Add an id to the css import and change the href on click with js

<html> <head>  <title>New UI Mockup</title>  <link href="dark.css" id="theme" rel="stylesheet">  <script>  var themeName = "dark";  function changeTheme(){   if (themeName == "dark"){    themeName = "light";   }   else{    themeName = "dark";   }   document.getElementById("theme").href = themeName + ".css";  }  </script> </head> <body> <div class="title">Change Theme Demo</div> <div class="button" id="changeButton" onclick="changeTheme()">Change Theme</div> </body></html>

change stylesheet by button click for specific element only

In This case we can make use of shadowRoot as an encapsulation for styles.

The idea is like adding a css file which contains a ton of styles to a page which only have the article element, obviously the other styles won't have any effect.

We can do the same using a shadowRoot put the article in it's own little world and add a file which contains more styles.

The code is heavily commented. If you have any question leave a comment :)

First on load we prepare the shadow Element:

const handleLoad = () => {

// Old Code for button handlers still needed
let style1 = document.getElementById('style1Button');
let style2 = document.getElementById('style2Button');
style1.addEventListener('click', handleClick);
style2.addEventListener('click', handleClick);


// New Code Below

// Select the article from the page
const article = document.querySelector('article');
// Create an empty div Element to work as a bucket
const placeholderElement = document.createElement('div');
// set it's id attribute to select it later
placeholderElement.setAttribute('id', 'placeholderElementShadowRot')
// replace the article with our div in the document
// the article element is not completly lose at this point
// we still have in the variable article
article.replaceWith(placeholderElement);
// attache a shadow to the div element
const shadow = placeholderElement.attachShadow({ mode: 'open' });
// sets the shadow's innerHTML equal to article outerHTML
shadow.innerHTML = article.outerHTML;


// create a link
const link = document.createElement('link');
// set it's href attribute to the first style file
link.setAttribute("href", 'style1.css');
// set the rel attribute
link.setAttribute("rel", "stylesheet");
// add the link to the shadow
shadow.appendChild(link)
};

And on button click

const handleClick = (event) => {
// Select our div we created before using the id
const placeholderElement = document.querySelector('#placeholderElementShadowRot');
// since we already attached a shadow
// we can use it through the property .shadowRoot
const shadow = placeholderElement.shadowRoot;

// based on which button we add the relevant style file
if (event.target.value === "Style 1") {
shadow.querySelector('link').setAttribute("href", "style1.css")
} else {
shadow.querySelector('link').setAttribute("href", "style2.css")
}
};

Note: You have a typo in your JS, The handler is called handleclick lower case click but you're adding an uppercase Click handleClick to addEventListener

How to edit CSS hashtags using JavaScript

When you edit the style of an element using the following:

document.getElementById("Doc1").style.opacity = "value";

You are setting the inline style of an element, not the styles applied by the #Image block.

If you'd like to edit the styles applied by the #Image block, there is some browser support for it using functions like insertRule() and deleteRule().

Instead of editing the styles applied by a stylesheet, I would add or remove classes from elements.

<div id="my-div" class="is-running">test</div>

<style>
.is-running { animation-play-state: running; }
.is-paused { animation-play-state: paused; }
</style>

<script>
document.getElementById('my-div').classList.remove("is-running");
document.getElementById('my-div').classList.add("is-paused");
</script>

how to alter a css class directly?

You can do all your css manipulation in a single style element you append to the head-
anything you put there takes precedence over the other stylesheets, and your users can 'backtrack' to the page defaults by deleting their changes, one at a time or all at once.

Using the last sheet (your new style element's rules) in the document.styleSheets collection, you can append new rules, delete old rules, or edit existing rules.

And you have a piece of text you can save on your server or in local storage for each user, possibly to add to the document the next time they visit.

How to change css rules of external stylesheet

You can acheive in following manner

var div = document.getElementById("newDiv");
div.style.position = "absolute";
div.style.top = "200px";
div.style.left = "200px";

likewise you can edit/add more css properties
See if this helps to alter CSS rules : Alter CSS Rules

Changing a CSS rule-set from Javascript

You can, but it's rather cumbersome. The best reference on how to do it is the following article: Totally Pwn CSS with Javascript (web archive link).

I managed to get it to work with Firefox and IE - I couldn't in Chrome, though it appears that it supports the DOM methods.ricosrealm reports that it works in Chrome, too.

Changing CSS properties via JavaScript

The stylesheets can be manipulated directly in JS with the document.styleSheets list.

Example:

<html>
<head>
<title>Modifying a stylesheet rule with CSSOM</title>
<style type="text/css">
body {
background-color: red;
}
</style>
<script type="text/javascript">
var stylesheet = document.styleSheets[1];
stylesheet.cssRules[0].style.backgroundColor="blue";
</script>
<body>
The stylesheet declaration for the body's background color is modified via JavaScript.
</body>
</html>

The example is by Mozilla Contributors and copied from:

  • Using dynamic styling information - Web API Interfaces | MDN


Related Topics



Leave a reply



Submit