Insert a CSS line as a new document stylesheet

I am dynamically creating a large stylesheet as a string and want to enter it in an iframe. I originally approached like this:

var css = '.newstyle { margin: 20px; } .newstyle2 { margin: 20px; }'; $('iframe').contents().find('head').append('<style type="text/css">'+css+'</style>'); 

Unfortunately, IE7 does not like this method. I'm not sure how else to approach this injection. Is there a cross-browser solution that will allow me to insert a ton of CSS from a string?

+4
source share
1 answer

You can use document.stylesheets for this purpose. This gives you access to the stylesheets on the page.

Check out this article: http://kentbrewster.com/creating-dynamic-stylesheets/ - it's a bit older, not jQuery-oriented, but I'm sure you can customize it to your needs. I used this technique a few years ago, and I believe that it worked fine in all browsers after some tweaking.

Here is a bit more information about the stylesheets property:

+2
source

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


All Articles