What is currently the best and easiest way to change CSS style using javascript?
I have several elements on the page with and in css
.colorManipul{filter: grayscale(33%);}
I want to change the value directly in CSS so that it is reflected on all required elements with this class
Thanks for the advice, link, example, ... just anything
CodePudding user response:
You can change the value of a CSS property with JS. To easily target a property you should target a CSS-Variable:
window.addEventListener('DOMContentLoaded', function() {
document.documentElement.style.setProperty('--body-bg', 'blue');
})
:root {
--body-bg: red;
}
body {
background: var(--body-bg);
}
However, this is harder to debug and a cleaner solution is to simply add a class to all elements with a certain class.
document.querySelectorAll('.colorManipul').forEach(el =>
el.classList.add('class-name')
);
CodePudding user response:
If you want to change percentage of grayscale value, you can use css variable and change it's value from JS For example:
CSS:
:root {
--grayscale: 33%;
}
.colorManipul {
filter: grayscale(var(--grayscale));
}
JS:
const grayscaleValue = 50;
root.style.setProperty('--grayscale', `${grayscaleValue}%`);