views:

978

answers:

6

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.

A: 

Check out the various JavaScript libraries. I recommend jQuery, check out the tutorial.

Then it's easy to add style (not really a class unless it already exists in the CSS):

<script>
$(document).ready(function() {
  // add 'style="height:30px;"' to the div with id="foo".
  $('#foo').attr("style", {height: "30px"}) 
});
</script>

Or add the same style to all elements with class="bar":

<script>
$(document).ready(function() {
  // add 'style="height:30px;"' to all elements with class="bar".
  $('.bar').attr("style", {height: "30px"}) 
});
</script>

If you want to create new CSS classes at run-time try: jQuery.Rule

beggs
+1 for jQuery...
Nimbuz
I want to use only basic javascript not JQuery.
Himadri
-1 for jQuery, it doesn't make anything easier in this case and you don't want to include an entire JS framework for every little snippet.
I.devries
@Vatos, how would you handle changing a large number of elements unless you assign each one an ID an use `getElementById()` like Dominic Rodgers' answer? There is no `getElementByClass()` built into Javascript? If it's only a few elements that are unique to be styled then ok but I would not want to add an ID to each of individual element if there are a lot.
beggs
A: 

Say you have some markup like this:

<div id="mydiv"><p>Some content</p></div>

This function would change the background-color CSS property of an element with ID mydiv to red.

<script type="text/javascript">
function change(){
    document.getElementById("mydiv").style.backgroundColor = "#ff0000";
}
</script>

I don't think there's a particularly easy way of actually creating CSS classes on the fly.

Dominic Rodger
I need to create css classes and assign to divs or table....
Himadri
Out of curiosity, why do you need to create classes on the fly? You can change the CSS properties of individual elements, and you can add a class to the set of classes that an element is "of", but I don't think there's a straightforward way of creating classes themselves on the fly, and I'm having difficulty imagining a use case for doing so.
Dominic Rodger
A: 

The following may be of interest. Not fully sure of its adoption by modern browsers, but it should do what you need it to do:

http://www.w3.org/TR/DOM-Level-2-Style/

jrista
+3  A: 

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';
I.devries
Nice.‌‌‌‌‌‌‌‌‌‌‌
beggs
+1  A: 

YUI has by far the best stylesheet utility I have seen out there. I encourage you to check it out, but here's a taste:

// style element or locally sourced link element
var sheet = YAHOO.util.StyleSheet(YAHOO.util.Selector.query('style',null,true));

sheet = YAHOO.util.StyleSheet(YAHOO.util.Dom.get('local'));


// OR the id of a style element or locally sourced link element
sheet = YAHOO.util.StyleSheet('local');


// OR string of css text
var css = ".moduleX .alert { background: #fcc; font-weight: bold; } " +
    ".moduleX .warn  { background: #eec; } " +
    ".hide_messages .moduleX .alert, " +
    ".hide_messages .moduleX .warn { display: none; }";

sheet = new YAHOO.util.StyleSheet(css);

There are obviously other much simpler ways of changing styles on the fly such as those suggested here. If they make sense for your problem, they might be best, but there are definitely reasons why modifying css is a better solution. The most obvious case is when you need to modify a large number of elements. The other major case is if you need your style changes to involve the cascade. Using the dom to modify an element will always have a higher priority. Its the sledgehammer approach and is equivalent to using the style attribute directly on the html element. That is not always the desired effect.

Russell Leggett
A: 

Hi maybe i am too much new in the css stuff and jquery. studying the rule API i dont manage to go further anyway. i would like to create dynamically with the rule api something like the stuff below. can anybody help me?

a:active { outline:none; }

:focus { -moz-outline-style:none; }

.weshop_overlay {
display:none; background-image:url(http://www.affiliate-applications.com/zanox/WeShop/Images/overlay/white.png); width:640px;
padding:45px; font-size:11px; }

.weshop_overlay .close { background-image:url(http://www.affiliate-applications.com/zanox/WeShop/Images/overlay/close.png); position:absolute; right:5px; top:5px; cursor:pointer; height:35px; width:35px; }

frank