Home  >  Article  >  Web Front-end  >  Can You Modify CSS Pseudo-Element Styles with JavaScript?

Can You Modify CSS Pseudo-Element Styles with JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 16:07:021009browse

Can You Modify CSS Pseudo-Element Styles with JavaScript?

Modifying CSS Pseudo-Element Styles Using JavaScript

Is it feasible to alter the styling of a CSS pseudo-element through JavaScript?

Consider the example of dynamically setting the color of the scrollbar using this code:

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

However, browsers respond with the following error: "Uncaught TypeError: Cannot read property 'style' of null."

Can this task be accomplished in a different manner?

In webkit browsers, you can achieve this by utilizing CSS Vars.

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

#editor::-webkit-scrollbar-thumb:vertical {
  background-color: #ccc;
  background-color: var(--scrollbar-background);
}

To manipulate this value in JavaScript:

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

For further examples of managing CSS variables with JavaScript, refer to the following resource: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/

The above is the detailed content of Can You Modify CSS Pseudo-Element Styles with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn