-1

emphasized text I am just studying and i want to create 100 css class dynamically

I want to do something like

for (i=0; i<100; i++) {
  // create css class
  const newBackgroundColor = dynamicBackgroundColor();
  const height = '100%';
  const width = '0%';
  // add all 3 attribute to newly created css
}

// and then down the road, I want to use these 100 css class to 100 dynamically created div
2
  • thank you but no.. first I am not sure why that post answer starts with "i am not sure why you want to create css w/ javascript.. how else would you create css dynamically?" .. Also, I need to recall 100 css name and apply to newly create 100 div later.. I am not sure link has that solution. Commented Jun 5, 2021 at 14:18
  • Yeah, that is a little ambiguous. Actually you usually use JS to create styles and append them to elements, rather than whole new css classes. Commented Jun 5, 2021 at 14:20

1 Answer 1

1

To answer your question, yes you can create dynamic css classes by the following

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `
.class1 {
 /* Some style */
}
`;
document.getElementsByTagName('head')[0].appendChild(style);

however in your case it would be easier to set the dynamic background color as inline style instead. While you generate the elements, just do element.style.backgroundColor = dynamicBackgroundColor()

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.