1

I am using document.write in a function to give different CSS to user's based on their choosing.

function blue() {
    document.write('<link rel="stylesheet" type="text/css"  href="http://ilam.irib.ir/documents/697970/237563314/blue.css" />');
}

I am calling the function from an anchor tag.

function color2(){
    document.getElementById("navigation").innerHTML +='<a class="myButton" onclick="blue()" background-color:"#05c8f2";></a>'; 
}

As you can guess, when the link is clicked, the page clears out and I get a blank page.

Is there any way to fix this problem? I don't want to stop page refreshing, I'm just trying to fix the problem in any way possible!

Note: don't ask why I'm adding code using JavaScript, and not directly into HTML code. This site is a large scale system and we just have access to JavaScript and CSS. So this is all we can do to edit our pages.

trincot
  • 317,000
  • 35
  • 244
  • 286
senaps
  • 1,374
  • 1
  • 14
  • 25
  • 1
    *"Is there any way to fix this problem?"* - Don't use `document.write()`, it's improper use after the DOM loads. They are plenty of other ways to do this. – Spencer Wieczorek Aug 30 '16 at 04:58

1 Answers1

2

document.write rewrites the body , as a result the only thing in your document remains is the css file you added and hence it is blank.

View this

Code from above link :-

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
  var head  = document.getElementsByTagName('head')[0];
  var link  = document.createElement('link');
  link.id   = cssId;
  link.rel  = 'stylesheet';
  link.type = 'text/css';
  link.href = 'http://website.com/css/stylesheet.css';
  link.media = 'all';
  head.appendChild(link);
}

Instead of rewriting while dom , we append the link element inside head tag

Community
  • 1
  • 1
Anmol Mittal
  • 843
  • 5
  • 12