Home > Web Front-end > JS Tutorial > body text

Can You Modify CSS Pseudo-Element Styles with JavaScript?

Linda Hamilton
Release: 2024-11-08 16:07:02
Original
1008 people have browsed it

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");
Copy after login

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);
}
Copy after login

To manipulate this value in JavaScript:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template