views:

107

answers:

2

I'm trying to load the inline style content of a remote xhtml page. I used load previously, but that doesn't work because it loads the css inside the body tag. Therefore, I'm trying to append the style to the head tag of my page.

The problem is that I cannot select the style tag using jQuery. Here's my code:

            jQuery.get(contenturl, function(data) {
                var css = jQuery(data).find('style').html();
                alert(css);
            });

The css variable is always null. Any ideas?

Thanks, Pete

A: 

Keep in mind this only works with local files. To do this with a remote file, you'll need to have a local PHP script that communicates with your jQuery script.

The following video tutorial demonstrates how to setup a local php file to do this very thing: http://sampsonvideos.com/video.php?video=24

Jonathan Sampson
+1  A: 

From jQuery manual:

jQuery( html, [ownerDocument] )

Simple elements without attributes, e.g., "<div />", are created via document.createElement. All other cases are parsed by assigning the string to the .innerHTML property of a div element. The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.

Therefore passing full HTML of a page to jQuery() function doesn't work. (Although it actually works in Opera, but I guess you want a cross browser solution.)

I'd recommend getting the CSS from <style> tags using simple regex like that:

jQuery.get(contenturl, function(data) {
  var styles = data.match(/<style.*?>[\s\S]*?<\/style>/ig);
  $("head").append(styles.join(""));
});

This should also be a whole lot of faster that creating the whole DOM tree.

Rene Saarsoo
Thank you! You helped me so much. I'm using this method to import remote java script to my framework page as well.