Home > Web Front-end > CSS Tutorial > How Can I Add a Stylesheet to the Head Section with JavaScript?

How Can I Add a Stylesheet to the Head Section with JavaScript?

Mary-Kate Olsen
Release: 2024-11-17 17:15:02
Original
486 people have browsed it

How Can I Add a Stylesheet to the Head Section with JavaScript?

Adding Stylesheet to Head Section Using JavaScript in Body

If you encounter a scenario where you need to add a CSS stylesheet to a website's head section but are restricted from editing the head directly, you can employ JavaScript code to dynamically inject the stylesheet. Despite the recommendation to insert the link element in the head section, most browsers handle it well within the body.

Here's how you can achieve this:

function addCss(fileName) {
  var head = document.head;
  var link = document.createElement("link");

  link.type = "text/css";
  link.rel = "stylesheet";
  link.href = fileName;

  head.appendChild(link);
}

addCss('{my-url}');
Copy after login

For a simpler approach with jQuery:

function addCss(fileName) {
  var link = $("<link />", {
    rel: "stylesheet",
    type: "text/css",
    href: fileName
  });
  $('head').append(link);
}

addCss("{my-url}");
Copy after login

Instead of appending to the end of the body, which is technically not the recommended location for the link element, you can also use JavaScript to insert it directly into the head section:

$('head').append('<link rel="stylesheet" type="text/css" href="{url}">');
Copy after login

By utilizing JavaScript, you can effectively add stylesheets to your website's head section, even if you don't have direct access to edit the head itself.

The above is the detailed content of How Can I Add a Stylesheet to the Head Section with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template