Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 538
Himadri Avatar asked Nov 12 '09 06:11

Himadri


People also ask

How do I apply CSS to dynamic content?

The better way is to add css classes which you want to add and then use addClass to add css dynamically.

Which method is used to add a CSS class 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.

How do you dynamically change a class in CSS style?

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.

Does CSS apply to dynamically created elements?

CSS is applied to dynamically created elements.


1 Answers

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'; 
like image 153
I.devries Avatar answered Oct 07 '22 14:10

I.devries