简体   繁体   中英

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

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

Live demo (click).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM