Search code examples
javascriptcsscss-selectorspseudo-elementselectors-api

Changing CSS pseudo-element styles via JavaScript


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.


Solution

  • 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');