How to dynamically create CSS class in JavaScript and apply?

Himadri picture Himadri · Nov 12, 2009 · Viewed 303k times · Source

I need to create a CSS stylesheet class dynamically in JavaScript and assign it to some HTML elements like - div, table, span, tr, etc and to some controls like asp:Textbox, Dropdownlist and datalist.

Is it possible?

It would be nice with a sample.

Answer

I.devries picture I.devries · Nov 12, 2009

Although I'm not sure why you want to create CSS classes with JavaScript, here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';