Reputation: 69
I have this selector in CSS for the .square class
.square:not(:hover){
}
And I want to add custom properties to it through JavaScript.
I tried doing this but it didn't work.
document.querySelectorAll('.square:not(:hover)').forEach((item) => {
item.style.transition = `background ${animation_delay}s`;
});
Is there any way to do it with VanillaJS ?
Upvotes: 1
Views: 698
Reputation: 329
document.querySelectorAll('.square:not(:hover)')
should return a list of nodes.
Nothing is wrong with the syntax.
Using chrome dev tools, first verify if .square:not(:hover)
exists in DOM.
Upvotes: 1
Reputation: 7464
The way you can access/modify a <style>
tag is as follows:
// suggest you add an id to your style tag
var style = document.querySelector('style');
var var sheet = style.sheet; // <-- CSSStyleSheet
var rules = sheet.rules; // <-- CSSRuleList
// keep the number of rules small/ordered
// in the sheet you want to mutate, so you can
// find them easily
rules[0].selectorText
// > selectorText: ".wmd-snippet-button span"
rules[0].style.backgroundColor
// > ""
rules[0].style.backgroundColor = 'black'
// > "black" // <-- (and see the change in the page!)
See more information at the MDN CSSStyleSheet and CSSRuleList pages.
*Note: this method will alter your rule in the style sheet, rather than the method you've shown of looping through all currently matching elements and applying an inline style to them.
Upvotes: 1