Javascript beginner: add dynamic style to javascript?

Possible duplicate:
How to create a <style> tag with Javascript

I am writing a dynamic form using java script. I want to add a style to java-script. I am writing code to add style. But it does not work. This is the code that I write in my project.

var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.body.appendChild(sheet);

Someone help me.

+5
source share
5 answers

Your code is ok. But I think you are not calling it at the right time, so name it when your body tag is loaded

 window.addEventListener('DOMContentLoaded',function(){
    var sheet = document.createElement('style'); 
    sheet.type="text/css"; 
    sheet.innerHTML = "body{color:red;}"; 
    document.body.appendChild(sheet);
    }, false);
+2
source

Why not just add style through the class?

.blue {
   background-color: blue;   
}​

document.body.className = 'blue';​

http://jsfiddle.net/kf8Nd/

If you really need an entire stylesheet, just add it to your header.

var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.head.appendChild(sheet); // head, not body
+1
source

, . , ! , , , . -

IE, FF Opera:

var css = 'h1 { background: red; }',
    head = document.getElementsByTagName('head')[0],
    style = document.createElement('style');

style.type = 'text/css';
if(style.styleSheet){
    style.styleSheet.cssText = css;
}else{
    style.appendChild(document.createTextNode(css));
}
head.appendChild(style);

:

document.getElementById("MyElement").className += " MyClass";

:

document.getElementById("MyElement").className = 
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/ , '' )
/* code wrapped for readability - above is all one statement */

onclick:

<script type="text/javascript">
    function changeClass()
    {
        // code examples from above
    }
</script>
...
<button onclick="changeClass()">My Button</button>


, ( jQuery), :

$j('#MyElement').addClass('MyClass');

$j('#MyElement').removeClass('MyClass');

$j('#MyElement').toggleClass('MyClass');

:

<script type="text/javascript">
    function changeClass()
    {
        // code examples from above
    }

    $j(':button:contains(My Button)').click(changeClass);
</script>
...
<button>My Button</button>

HTML JS, , , / , .

+1

,

var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.head.appendChild(sheet);
0
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = 'body{color:red;}';
document.getElementsByTagName('head')[0].appendChild(style);
0

All Articles