How to insert css into a document via ajax?

So, I get the data through the jquery ajax method. The data obtained are as follows:

<html> <head> <style> body { color: red; font-weight: bold; } #someElement { color: blue; padding: 1em } </style> </head> <body> <div id="header">Super</div> <p>blah blah blah</p> <div id="footer">Stuff</div> </body> </html> 

How to extract a style and paste it into the current document that is making an ajax call? I tried all kinds of jquery spells, but it is not. I am now extracting css via regex, but I'm not sure how to put css in the current page:

 $.ajax({ url: '/template.html', success: function(data) { $("#header").html( $(data).find('#header').html() ); $("#footer").html( $(data).find('#footer').html() ); var re = /<style>((?:[\n\r]|.)+)<\/style>/m; var css = re.exec(data); // What to do with the css?? return; } }); 

First I had a stylesheet, and then the following was simply done:

  if($.browser.msie) { $('head').html( '<link rel="stylesheet" href="http://c.this/template.css" type="text/css" />'+ $('head').html() ); } else { $('head').prepend('<link rel="stylesheet" href="http://c.this/template.css" type="text/css" />'); } 

This works, with the exception of IE8, it causes some problems.

+7
source share
3 answers

Instead of using a regular expression, you can use .filter() to search for the <style/> , just use document.getElementsByTagName("head")[0] to add HTMLStyleElement

 $.ajax({ type: 'POST', url: "/echo/html/", data: { html: postHtml }, success: function(data) { var style = $(data).filter("style").get(0); document.getElementsByTagName("head")[0].appendChild(style); $("#header").html($(data).filter('#header').html()); $("#footer").html($(data).filter('#footer').html()); } }); 

Jsfiddle working example

tested on IE8 / 9, chrome, firefox

+1
source

Could you not create a style tag and insert it into the DOM just like you would insert any other tag?

 $('<style type="text/css"></style>') .appendTo("head") .html("your css text here"); 

* Have not tried this

EDIT:

Oh, I see you are trying to extract css from an HTML page. Is there a way that you can only get CSS without having to load another page?

+2
source

Are you trying to parse a third-party page, by accident?

If this is not the case, then why don't you just load the CSS regardless of the page invoking your ajax. It is then available to all elements on the page - even new ones delivered by ajax.

If you are trying to analyze the pages of other sites, you will need to create a proxy service.

+2
source

All Articles