How to replace CSS files on the fly with JavaScript?

Spread the love

To replace CSS files on the fly with JavaScript, we can create a new link element.

For instance, we write

function changeCSS(cssFile, cssLinkIndex) {
  const oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
  const newlink = document.createElement("link");
  newlink.setAttribute("rel", "stylesheet");
  newlink.setAttribute("type", "text/css");
  newlink.setAttribute("href", cssFile);

  document
    .getElementsByTagName("head")
    .item(cssLinkIndex)
    .replaceChild(newlink, oldlink);
}

to add the changeCSS function.

In it, we get the link element and get the link element to replace with the item meethod and the cssLinkIndex index.

Then we create a new link element with createElement.

We add the attributes for the new element with setAttribute.

And then we get the head element with getElementsByTagName and item.

We then call replaceChild to replace the oldLink element with the newLink link element.

Leave a Reply

Your email address will not be published. Required fields are marked *