0
Can i use JS DOM to change a .css file?
I mean, if we can do "document.element.innerHTML" to change the content of some tag, i wonder if we can do "cssdocument.selector.property.innerCSS" or something like that. I know that we can change inline style with "element.style.property" but it is not consistent. At least a library please :P
7 Answers
+ 1
Sorry bozo programaçÔes if I've misunderstood you but here are a couple of things you can try to achieve different things.
1. Completely change a CSS file dynamically (e.g. by user interaction) using JavaScript.
Say you had 2 CSS files, main.css and alternative.css, you linked main.css in your HTML and gave the link an id of "style". In JavaScript, you can do:
document.querySelector(â#styleâ).getAttribute(âhrefâ) === âmain.cssâ ? theme.setAttribute(âhrefâ, âalternative.cssâ) : theme.setAttribute(âhrefâ, âmain.cssâ);
2. Add CSS rules dynamically:
// this code assumes you want to add the rules to the first stylesheet (see index number)
// say you have a div with a class called 'box' and some text in it, you can do this in JavaScript
document.styleSheets[0].insertRule(".box {color: red}", 0)
You will see the text going red, but only if it's not overridden by a rule in the original CSS file. Obviously you can do a lot more than change colour but it's just to show a simple example.
+ 3
CamelBeatsSnake YEEEASSS THATS IT THANK YOU SOOOO MUCH <3333 i wanted the 2nd one (add css rules dynamically) thanks again :>
0
Why not use CSS classes and change those dynamically with your JavaScript, rather than just changing properties inline as you've suggested in your question description?
CSS wasn't really built to be dynamic. JavaScript is much more suited for that.
So, you can do things dynamically, like change CSS classes, individual style properties, or even change the stylesheet itself.
0
CamelBeats that's a good one but i am not entirely conviced yet, sorry
0
bozo programaçÔes I'm curious as to what the specific problem you're trying to solve is. I'm pretty sure it can be solved using conventional methods using JavaScript and CSS.
Could you please give a code example of what you're trying to achieve?
0
CamelBeatsSnake huh, i don't have any problem or code, i just wanted to know...
but here is an example: if i wanted to change a .css file that is linked in 2 or more html pages, i wish i could change it with javascript, just interacting with the user
0
bozo programaçÔes Awesome đ Glad I could help.