How to set a pseudo element directly to html with JavaScript

Viewed 103

I have to solve a challenge and it requires me to write all the html, css and JS all in one JS file. I'm having trouble figuring out how can I set a pseudo element to a 'div' using JS.

The code for setting my div is:

let myDiv = document.createElement('div')
myDiv.className = 'cart-container'
myDiv.style.cssText = "height: 440px; width: 400px; margin: auto; overflow-y:auto;"

in CSS the pseudo elements would look like this:

.cart-container::-webkit-scrollbar{
  width: 10px;
}

.cart-container::-webkit-scrollbar-thumb{
  border-radius: 5px;
  background-color: #30808d;
  height: 100px;
}

how could I inset that CSS code to my 'div' using JS instead of using CSS?

1 Answers

You can make use of CSSStyleSheet.insertRule() method to insert styles for pseudo elements. I've added a small example below on how to make use of it:

document.styleSheets[0].insertRule("::-webkit-scrollbar { width: 100px; background-color: green; }");
#test {
  height: 2000px;
  background-color: red;
}
<div id="test"></div>

Related