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

How to Modify CSS Pseudo-Element Styles with JavaScript Without 'Uncaught TypeError: Cannot read property 'style' of null'?

Susan Sarandon
Release: 2024-11-09 04:14:02
Original
560 people have browsed it

How to Modify CSS Pseudo-Element Styles with JavaScript Without

Modifying CSS Pseudo-Element Styles with JavaScript

While attempting to adjust the color and visibility of the scrollbar using JavaScript, it's common to encounter the error "Uncaught TypeError: Cannot read property 'style' of null". This occurs because websites have disabled scrolling by default, causing the scrollbar elements to not exist.

To work around this limitation, you can employ the CSS Vars technique. This method involves defining fallback values in your CSS and dynamically manipulating them using CSS variables in JavaScript.

In your CSS, define the scrollbar styles with fallback values as follows:

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

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

Then, in your JavaScript, modify the variable that controls the scrollbar background color:

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

This approach allows for dynamic modification of scrollbar styles without encountering "null" errors. Keep in mind that this technique may not be supported in all browsers, so consider graceful degradation for older browsers.

The above is the detailed content of How to Modify CSS Pseudo-Element Styles with JavaScript Without 'Uncaught TypeError: Cannot read property 'style' of null'?. 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