1

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 ?

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.