-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
hanabbs
  • 149
  • 6
  • 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. – hanabbs Jun 05 '21 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. – Kinglish Jun 05 '21 at 14:20

1 Answers1

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()

Victor Fernandes
  • 386
  • 1
  • 4
  • 15