0

I have a javascript file, and one of its functions is to create some HTML using javascript.

The HTML is created at runtime and creates the following element:

var oBox = document.createElement("notifiedusersbubble");
oBox.style.color="#808080";
oBox.style.display = "none";
oBox.style.position= "absolute";
oBox.style.width="200px";
oBox.style.border = '1px solid black';
oBox.style.background = "#DDEFF1";
oBox.style.fontFamily="arial,sans-serif";
oBox.style.padding="2px 2px 2px 4px";

Instead of leaving all the styling inside the javascript file, I want to put t in the CSS file and reference it from there.

The problem is, I do not know how to do this using javascript. I know that to do so using HTML I would write the following inside the <head> tag:

<link href="style.css" rel="stylesheet" type="text/css" />
  • 1
    possible duplicate: (http://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript) – Joanes Dec 05 '14 at 09:37

1 Answers1

0

You can create a link element just like any other element:

var link = document.createElement('link');
link.rel = "stylesheet";
link.type = "text/css";
link.href = "style.css";
document.querySelector("head").appendChild(link);

...but that said, I would normally expect you to leave that to the page author, just list it as a requirement of your script that the CSS must be put on the page — not least because it lets them combine that CSS with other CSS to avoid lots of HTTP requests, etc. That's what every major framework/library (jQuery UI, Bootstrap, etc.) does.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • it says 'object does not support property or method queryselector' –  Dec 05 '14 at 09:45
  • @Alex: Wow, you're using a **really** old browser, even IE8 has `querySelector`. You can use `document.getElementsByTagName("head")[0].appendChild(link);` instead. – T.J. Crowder Dec 05 '14 at 09:52