Changing CSS pseudo-element styles via JavaScript

JavascriptCssCss SelectorsPseudo ElementSelectors Api

Javascript Problem Overview


Is it possible to change a CSS pseudo-element style via JavaScript?

For example, I want to dynamically set the color of the scrollbar like so:

document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");

and I also want to be able to tell the scrollbar to hide like so:

document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";

Both of these scripts, however, return:

> Uncaught TypeError: Cannot read property 'style' of null

Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.

Javascript Solutions


Solution 1 - Javascript

If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.

So in your CSS you can write:

#editor {
  --scrollbar-background: #ccc;
}

#editor::-webkit-scrollbar-thumb:vertical {
  /* Fallback */
  background-color: #ccc;
  /* Dynamic value */
  background-color: var(--scrollbar-background);
}

Then in your JS you can manipulate that value on the #editor element:

document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));

Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/

Solution 2 - Javascript

To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.

Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js

https://stackoverflow.com/questions/7330355/javascript-set-css-after-styles/7330454#7330454

var addRule = (function (style) {
    var sheet = document.head.appendChild(style).sheet;
    return function (selector, css) {
        var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
            return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
        }).join(";");
        sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
    };
})(document.createElement("style"));

addRule("p:before", {
	display: "block",
	width: "100px",
	height: "100px",
	background: "red",
	"border-radius": "50%",
	content: "''"
});

sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.

Solution 3 - Javascript

> EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.

The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:

CSS

.hidden-scrollbar::-webkit-scrollbar {
   visibility: hidden;
}

JavaScript

document.getElementById("editor").classList.add('hidden-scrollbar');

To later remove the same class, you could use:

document.getElementById("editor").classList.remove('hidden-scrollbar');

Solution 4 - Javascript

I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:

/*CSS Part*/
:root {
    --selection-background: #000000;
}
#editor::selection {
    background: var(--selection-background);
}

//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");

Solution 5 - Javascript

You can't apply styles to psuedo-elements in JavaScript.

You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.

Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.

Solution 6 - Javascript

I posted a question similar to, but not completely like, this question.

I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.

My question is at https://stackoverflow.com/questions/32981211/retrieving-or-changing-css-rules-for-pseudo-elements

Basically, you can get a style via a statement such as:

document.styleSheets[0].cssRules[0].style.backgroundColor

And change one with:

document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;

You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.

I've found this works for pseudo elements as well as "regular" element/styles.

Solution 7 - Javascript

An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.

The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:

"#editor::-webkit-scrollbar-thumb:vertical {
    background: --editorScrollbarClr
}

Change the value in JavaScript:

document.body.style.setProperty(
    '--editorScrollbarClr', 
     localStorage.getItem("Color")
);

The same can be done for other properties.

Solution 8 - Javascript

Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.

Lots of good examples here: https://stackoverflow.com/questions/351633/loading-css-rules-dynamically-in-webkit-safari-chrome

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question木川 炎星View Question on Stackoverflow
Solution 1 - JavascriptWes RuvalcabaView Answer on Stackoverflow
Solution 2 - Javascriptuser748221View Answer on Stackoverflow
Solution 3 - JavascriptChris FritzView Answer on Stackoverflow
Solution 4 - JavascriptTazExprezView Answer on Stackoverflow
Solution 5 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow
Solution 6 - JavascriptSimonTView Answer on Stackoverflow
Solution 7 - JavascriptLee GoddardView Answer on Stackoverflow
Solution 8 - JavascriptHemlockView Answer on Stackoverflow