Put CSS in the header using JS

I need to put CSS (block in title) with Javascript or JQuery in the title of the current page. Css is in text format like this (it comes from the 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 a header block using JavaScript as follows:

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

+4
source share
6 answers

Using jQuery, you can do something like this:

  $('<style type="text/css"> ' + myCSS + '</style>').appendTo('head'); 
+3
source

You can use jquery for this. Do something like this:

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

Using jQuery you can make an append

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

+1
source

Yes, maybe check out this guide so you can understand how to do it: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

Edit: if you don't need to run the script in the body, a similar question arises 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); } 
0
source

I found this lib can help:

https://github.com/cssobj/cssobj

It maps CSSOM from JS to <head> , and you can change the rules directly from the JS object.

DEMO: https://cssobj.imtqy.com/cssobj-demo/

0
source

Try the following:

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

Source: https://habr.com/ru/post/1385375/


All Articles