Luke
Luke

Reputation: 3541

Can Javascript in the HTML body manipulate the head element?

I've written a widget that on the backend allows you to select a file from your google drive account via the OAuth2 / Google Picker UI

Because the widget is rendered on the front end in the body of the webpage I cant include the style tag and need to add it dynamically to the head.

My attempted solution was to build a self invoking script that I could append to the body, so when the widget content is loaded it can add the necessary style tag into the page head

Here's my code.

var stylesheet = 'body{background-color:yellow}';

var styleScript = "<scrip" + "t>(function(){var style = document.createElement('style');style.type = 'text/css';if (style.styleSheet) { style.styleSheet.cssText = '" + stylesheet + "';} else {style.innerHTML = '" + stylesheet + "';} document.getElementsByTagName('head')[0].appendChild( style );console.log(style);}());</sc"+"ript>";

console.log(styleScript);

document.body.innerHTML = styleScript;

jsfiddle

Upvotes: 0

Views: 489

Answers (1)

m59
m59

Reputation: 43755

var css = 'p { background: blue; }';
var style = document.createElement('style');
style.textContent = css;
document.head.appendChild(style);

Live demo (click).

Upvotes: 1

Related Questions