Dynamically Append Stylesheet to Head Using JavaScript
In certain scenarios, accessing and editing the head section of a web page may be restricted. However, there remains a need to add additional stylesheets to enhance the visual appearance of the site. This raises the question: can we use JavaScript to accomplish this task, ensuring that the stylesheet is inserted after the head tag?
To address this challenge, JavaScript offers a versatile solution:
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('{myUrl}');
Alternatively, if you prefer jQuery:
function addCss(fileName) { var link = $("<link />", { rel: "stylesheet", type: "text/css", href: fileName }); $('head').append(link); } addCss("{myUrl}");
These methods dynamically append the stylesheet link element to the head section of the HTML document, enabling you to add additional styles to your website even if access to the head section is restricted.
The above is the detailed content of How Can I Dynamically Append a Stylesheet to the Head Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!