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!

6 Answers 6

3

Using jQuery, you could do something like this:

 $('<style type="text/css"> ' + myCSS + '</style>').appendTo('head');
Sign up to request clarification or add additional context in comments.

Comments

2

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

$("head").append("<style type=\"text/css\">" + {your content} + "</style>");

Comments

1

Using jQuery, you should be able to do an append

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

Comments

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);
 }

Comments

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/

Comments

-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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.