Home > Article > Web Front-end > Can You Modify CSS Pseudo-Element Styles with 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!