user2683117
user2683117

Reputation: 11

Appending a stylesheet to the head of an html document using JavaScript

I'm attempting to add jQuery to an html document before downloading it. I need to append the following to the head of the document:

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/themes/base/jquery-ui.css"/>

I have attempted to use the following to do this, but all I end up with is an empty pair of tags in the document:

var head = content.document.getElementsByTagName('head')[0];
var jqstyle = document.createElement("link");
    jqstyle.rel = "stylesheet";
    jqstyle.type = "text/css";
    jqstyle.href = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/themes/base/jquery-ui.css";
head.appendChild(jqstyle);

Could anybody tell me what I need to do differently?

Thank You

Upvotes: 1

Views: 4385

Answers (2)

stmcallister
stmcallister

Reputation: 1719

This would also work.

$('head').append('<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jquery/ui/1.7.1/themes/base/jquery-ui.css"/>');         

Upvotes: 0

enhzflep
enhzflep

Reputation: 13089

As Fabricio pointed out, you've missed two letters (u and i) from the url of the css file.

This works fine here (note the difference between the url in the comment and the one actually used):

// want to create this and add to the doc head
// <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/themes/base/jquery-ui.css"/>
var link = document.createElement('link');
link.rel = "stylesheet";
link.type = "text/css";
link.href = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css";
document.head.appendChild(link);

Upvotes: 2

Related Questions