Home > Software engineering >  Dynamically link a css
Dynamically link a css

Time:06-21

My folder structure look like below:

|--js
  |-- main.js
|--css
  |--main.css
|--Folder1
  |-- c.html
|--Folder2
  |-- d.html
|--a.html
|--b.html

All the html file will be linked to the main.js and I have something like below in the js to dynamically link the main.css but this only work for html a and b. For html c and d, it expect the css folder is within the same folder.

var theorigin = window.location.origin;
var thefile = window.location.pathname.split("/").pop();
var folder = window.location.pathname.replace(thefile, "");
var newdest = theorigin   folder;

var link = document.createElement("link");
link.href = newdest   "../css/main.css";
link.type = "text/css";
link.rel = "stylesheet";
document.head.appendChild(link);

Anyone know how to achieve that? Dynamically link the css to the html regardless the folder?

Note: I know I can link the css in the html that put inside a folder by doing this<link href="../css/main.css" rel="stylesheet" />, but for some reason I dont want to do that.

CodePudding user response:

Just Use below code. its directly point to root (/).

link.href = "/css/main.css";

CodePudding user response:

I think you have made the code overly complicated. Why not just:

var link = document.createElement("link");
link.href = "/css/main.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
  • Related