I\'m trying to create a dynamic page using external .css pages where the page color will get changed. Below is my code. But when I click the href
, I am not gett
Use this code
document.getElementsByTagName("head")[0].appendChild('<link href="style.css" rel="stylesheet" type="text/css" />');
it might work, your code may working but due to some another css it won't reflected.
' document.createElement("link") ' creates hyper link object, not css style tag() element, so you are not able to apply this dynamically
correct me if i am wrong
Try adding a style line in your html and just using @import in the css to get the new file
Tim Goodman's answer is correct, but instead of fileref.href = "filename";
it should be fileref.href = filename;
Otherwise you're trying to load a file with the name "filename" rather than what you passed to the script.
Alternately, if you're willing to use the jQuery library, this can be accomplished in one line:
$("head").append("<link rel='stylesheet' id='extracss' href='"+filename+"' type='text/css' />");
Also, about the first version of your script using setAttribute: Most browsers will only take setAttribute with an empty third parameter because of the way the spec is set up:
fileref.setAttribute("href", filename, "");
Change this
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a>
to
<a href="javascript:void(0)" onclick="loadjscssfile('oldstyle.css','css');">Load "oldstyle.css"</a>
I belive the onclick, event to href will reload the new file.
First of all, you can't have an anchor element in the <head>
section. Secondly, are you sure your CSS path is correct? I'm asking because you already have a reference to css/newstyle.css
but your are trying to load newstyle.css
. Are you sure it's not css/newstyle.css
?
Edit: Here is a working example of your own code. There is something else wrong. Try to statically link the CSS and see if you are getting the styles. If not, there may be errors in your stylesheet.
By statically linking the stylesheet, I meant to say add this in your page instead of loading from javascript
<link rel="stylesheet" type="text/css" href="css/oldstyle.css" />