4

I have to put CSS (block in the header) with Javascript or JQuery in the header of the current page. The css is in text format, like this (it comes from a server):

label { font-family: Verdana, sans-serif; font-size: 12px; display: block; }
input { padding: 3px 5px; width: 250px; margin: 0 0 10px; }
input[type="file"] { padding-left: 0; }
input[type="submit"] { width: auto; }

I want to put this CSS in the header block, with JavaScript like this:

<meta name="author" content="" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<style type="text/css">
    label { font-family: Verdana, sans-serif; font-size: 12px; display: block; }
    input { padding: 3px 5px; width: 250px; margin: 0 0 10px; }
    input[type="file"] { padding-left: 0; }
    input[type="submit"] { width: auto; }
</style>
</head>

Is it possible?

Thanks!

benske
  • 3,922
  • 4
  • 24
  • 22

6 Answers6

3

Using jQuery, you could do something like this:

 $('<style type="text/css"> ' + myCSS + '</style>').appendTo('head');
RoccoC5
  • 4,185
  • 16
  • 20
2

You can use jquery to do this. Do something like this:

$("head").append("<style type=\"text/css\">" + {your content} + "</style>");
gabitzish
  • 9,535
  • 7
  • 44
  • 65
1

Using jQuery, you should be able to do an append

$('head').append(' //stick the whole thing here ');

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
0

I found this lib may help:

https://github.com/cssobj/cssobj

It's render CSSOM from JS into <head>, and you can change rules directly from JS Object.

DEMO: https://cssobj.github.io/cssobj-demo/

James Yang
  • 1,306
  • 4
  • 15
  • 25
0

Yes it's possible, checkout this tutorial so you can understand how it's done: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

Edit: If you don't need to run the script in the body, there is a similar question here: Add CSS to <head> with JavaScript?

function addcss(css){
    var head = document.getElementsByTagName('head')[0];
    var styleElement = document.createElement('style');
    styleElement.setAttribute('type', 'text/css');
    if (styleElement.styleSheet) {   // IE
        styleElement.styleSheet.cssText = css;
    } else {                // the world
        styleElement.appendChild(document.createTextNode(css));
    }
    head.appendChild(styleElement);
 }
Community
  • 1
  • 1
alessioalex
  • 62,577
  • 16
  • 155
  • 122
-1

Try with this:

<script type="text/javascript">
 var css = document.createElement('style');
 css.type = 'text/css';

 var styles = 'your_server_response_css_rules';

 if (css.styleSheet)
     css.styleSheet.cssText = styles;
 else 
     css.appendChild(document.createTextNode(styles));

 document.getElementsByTagName("head")[0].appendChild(css);
</script>
pna
  • 5,651
  • 3
  • 22
  • 37