3

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?

rams141
  • 41
  • 1
  • Just a side note: are you sure `myDiv.className = 'cart-container'` is correct? Shouldn't it be `myDiv.classList.add('cart-container')` or `myDiv.setAttribute('class', 'cart-container')`? – secan Jul 09 '21 at 13:18
  • 2
    @secan - that approach is a bit older and `classList` is probably preferred today, but [`className`](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) does work for this purpose. – Alexander Nied Jul 09 '21 at 13:20
  • @AlexanderNied, thanks; I did not know that :) – secan Jul 09 '21 at 13:22
  • Possible duplicate of [Changing CSS pseudo-element styles via JavaScript](https://stackoverflow.com/questions/4481485/changing-css-pseudo-element-styles-via-javascript) – Alexander Nied Jul 09 '21 at 13:26
  • For what concerns your actual question, I think you will have to use one of the approaches suggested in the answers to this question: https://stackoverflow.com/q/311052/14201528 (the question is about pseudo-classes but you can apply the same logic for pseudo-elements too) – secan Jul 09 '21 at 13:39

1 Answers1

0

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>
Nilanshu96
  • 157
  • 6
  • would this assume I don't have a css file? for this purpose I cant use one everything created needs to be in JS – rams141 Jul 09 '21 at 14:06
  • @rams141 yes the css here has no role at all. It's just there to have a large enough div to display the scrollbar. Even if you create everything from JS, the document will still have a stylesheet in which you can insert rule just the way you add styles in css. – Nilanshu96 Jul 09 '21 at 14:38