Adding pseudo-class to elements with JavaScript

Hi, does anyone know of an easy way to add pseudo-class styles to an element created with JavaScript? For example:
const button = document.createElement('button');
button.style.backgroundColor = 'lightblue';
button.style.color = '#333';

// add hover state?
const button = document.createElement('button');
button.style.backgroundColor = 'lightblue';
button.style.color = '#333';

// add hover state?
How can I add a hover state following this same approach? I ran into this situation and I didn't know how to make it work, although I will ultimately use React later on. Still just for prototyping quickly I like using vanilla JS. There seem to be a lot of weird workarounds that I rather not get into.... so if someone knows of an easy way, please share? Thanks! 😄
5 Replies
b1mind
b1mind•2y ago
b1mind
b1mind•2y ago
If I understand you it should give you ideas at the very least.
Joao
JoaoOP•2y ago
I think that's pretty much what I was looking for, really neat Mmmm definitely interesting and learned a thing or two, but not quite actually what I need. This still involves having a selector for the hover state in CSS, but I want to make that selector right in JavaScript. But thanks for sharing it's good to know another way to do this
b1mind
b1mind•2y ago
Yea far as I know you can't target pseudo elements in JS so not sure how you would add a hover selector to it 🤔
Joao
JoaoOP•2y ago
Yeah, it's silly I already wasted more time trying to figure this out than it would take to write a single css rule 😄
Want results from more Discord servers?
Add your server