Himadri Himadri - 1 year ago 137
CSS Question

How to dynamically create CSS class in JavaScript and apply?

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 Source

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.getElementById('someElementId').className = 'cssClass';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download