Generally you might not need/want to do this, in fact you’ll rarely change elements of ‘head’ tag using Java script. But this is for those who are left with no other choice. It is really simple, JQuery provides a methods ‘text() / html()’ which will allow you to change content of any DOM element. To change the ‘Style’ tag content we can use ‘text()’ method, sample code is provided below.
To test follow this link: http://jsfiddle.net/tM96J/1/
<html>
<head>
<style id="myStyles" type="text/css">
.header {
color: blue;
}
</style>
<script type="text/javascript">
$("#myButton").click(function(e) {
$("#myStyles").text(".header { color: green }");
});
</script>
</head>
<body>
<h2 class="header">My Page Heading</h2>
<input type="button" id="myButton" value="Click Me"/>
</body>
</html>
Ideally you’d expect this code to work, but this code will not work in IE8; for some reason it seems you can not use ‘text()’ method to change ‘style’ tag contents in IE8. So work around for it - remove the ‘style’ completely and add it again with new content as shown below
<html> <head> <style id="myStyles" type="text/css"> .header { color: blue; } </style> <script type="text/javascript"> $("#myButton").click(function(e) { // $("#myStyles").text(".header { color: green }"); var headerEl = $("#myStyles").parent(); $("#myStyles").remove(); $(headerEl).append("<style id='myStyles' type='text/css'> .header {color: green;}</style>"); }); </script> </head> <body> <h2 class="header">My Page Heading</h2> <input type="button" id="myButton" value="Click Me"/> </body> </html>
To test follow this link: http://jsfiddle.net/tM96J/1/
Comments
Post a Comment