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.
The better way is to add css classes which you want to add and then use addClass to add css dynamically.
You can use Javascript for adding a class: setAttribute and className both method are used to set class (class attribute), these method are not used to adding another class with existing one.
To do the first thing I use $(". className"). css() method, but it changes style only for those elements that already have className class, i.e. if I later add className to an element its style won't be new.
CSS is applied to dynamically created elements.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With