0

Let's say I'm working on a large page. I want to predefine some CSS styles as variables in JavaScript that I can use later. Is it possible? What would the syntax be?

I'm trying to do something like this:

var box = document.querySelector('.box'); 
var styleColor = style.color;
var red = "red"

box.onclick = function(){styleColor.red;}

I'm aware you can do it like this:

var box = document.querySelector('.box');

box.onclick = function(){box.style.color = "red";}

But I want to cache the CSS so It can be re-used later. Is this possible, if so what would the syntax look like?

1 Answer 1

1

Write your css in a normal css file. For instance:

.myRedClass { color: red; }

Then append a class to elements you want to be red in javascript as follows

var element = document.getElementById(elementId);
element.className += " " + "myRedClass";
Sign up to request clarification or add additional context in comments.

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.