Using Javascript to insert css link into the head of a page - javascript

I 3rd party site that includes this script:
var foo = "Hello World!";
(function() {
var foo = "Goodbye World!";
document.write("<p class='something'>Inside our anomymous function foo means '" + foo + '".</p>');
})();
I would now like to insert (using pure javascript) an external reference to a style sheet. How can this be done?
Using jquery you could do it like this:
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
however I need to keep this pure javascript.

Quickly tried below in Chrome and it works..
var styleEl = document.createElement("link");
styleEl.type = "text/css";
styleEl.href = "style.css";
document.getElementsByTagName('head')[0].appendChild(styleEl);

Place a <script> tag in the head like this:
<head>
<script>
document.write('<link rel="stylesheet" type="text/css" href="style.css">');
</script>
</head>
The document.write() function appends whatever text you have as the parameter right where the script is.

You can do it at runtime like this:
var css = document.createElement("LINK");
css.href = "style.css";
css.type = "text/css";
document.head.appendChild(css);
Edit: document.head is compatible with normal browsers and IE9+

Related

Change stylesheet based on Javascript if else statement

I'm making a page with lots of iframes on it, the websites in the iframes have ads in them and to make the page more viewable to people with adblock, I need to display different stylesheets.
Basically what I want to do is.. if adblock (display this stylesheet) else (display this stylesheet).
I have the code working to detect if adblock is present, but when I try to do the if else statement..the whole page is blank. Here's the code:
<script>
(function(){
if($("#fakead").css('display')=="none")
{
document.write("<link href='css/adblock.css' rel='stylesheet' type='text/css'>")
}
else
{
document.write("<link href='css/noadblock.css' rel='stylesheet' type='text/css'>")
}
});
</script>
I'm extremely new to Javascript so my apologies if the code is terrible.
Thanks for any help
You should not use document.write method. As I see you use jQuery, so in jQuery you can do like this:
$( function() {
if($("#fakead").css('display')=="none") {
$("<link href='css/adblock.css' rel='stylesheet' type='text/css'/>").appendTo( 'head' );
} else {
$("<link href='css/noadblock.css' rel='stylesheet' type='text/css'/>").appendTo( 'head' )
}
});
Please note: link element should be placed in <head> section. Read more in w3c.
Pure JS option:
var el = document.createElement("link");
el.type = "text/css";
el.rel = "stylesheet";
el.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(el);

Adding a Style Sheet to a document using jQuery

jQuery(document).ready(function($) {
/******* Load CSS *******/
$('head').append('<link rel="stylesheet" type="text/css" media="all" href="'+('https:' == document.location.protocol ? 'https://' : 'http://') +'thesite.com/api/widgets/tghd/pages.css">');
});
The above code is what I use to add the style sheet to the document. The code inspector shows that the code has been added but the console does not display that the browser has requested the document and the styles do not take affect.
How can I add a style sheet to an already loaded document and have it take affect.
BTW. if it matters, I am using this code for a widget so I will be used across multiple domains.
Thank You in advance for any help!
try this:
(function () {
var li = document.createElement('link');
li.type = 'text/css';
var href='http://' + 'thesite.com/api/widgets/tghd/pages.css';
li.setAttribute('href', href);
var s = document.getElementsByTagName('head')[0];
s.appendChild(li, s);
})();
OK after doing a few tests, I finally figured out what was going on. This original code was provided by: #Vicky Gonsalves
var li = document.createElement('link');
li.type = 'text/css';
var href=('https:' == document.location.protocol ? 'https://' : 'http://') +'thesite.com/api/widgets/pages.css';
li.setAttribute('href', href);
li.setAttribute('rel','stylesheet');
var s = document.getElementsByTagName('head')[0];
s.appendChild(li, s);
The changes that I made to this are:
I added the http and https switch to help with different connection types
added the attribute li.setAttribute('rel','stylesheet'); <-- which I believe fixed the problem.

Set entire page's css on click?

Does anyone know how I can change the entire document's CSS file on click? I've searched around but only found a few results on setting a class/ID's CSS, not the entire document. My website has two themes, light/dark, and I want to load up "light.css" or "dark.css" from two links.
Thanks.
You need to change the src of the the link tag, which controls the styles. For example, you probably have this in your head tag:
<link rel="stylesheet" href="light.css">
You need to change the href attribute of the link tag to "dark.css" when you click something. You can do that like this:
document.getElementById('id-of-element').addEventListener('click',function(){
document.getElementsByTagName('link')[0].setAttribute('href',isDark?'light.css':'dark.css');
isDark=isDark?false:true;
}
IMPORTANT: you need to set isDark to false or true before this code, depending on whether the page is supposed to be dark or light in the beginning. You also need to change id-of-element to the id of the element that should be clicked to toggle the state of the page.
I think this is better than the other answers because it is simpler and uses no jquery.
EDIT: I accidentally had the src attribute instead of the href one before. I now updated it to be correct.
Yeah, you can do using theming. But the changing of CSS is limited to the <body> tag.
$("a.theme").click(function(){
$("body").addClass("dark");
});
I have used jQuery library to make the coding easier. And it is not a good idea to switch CSS rather, you can change the classes.
Demo
You can check out the working demo in jsBin.
Check out this answer for more details: Selecting a web page look and feel without reloading, with one CSS.
Try something like this:
Light
Dark
<script type="text/javascript" charset="utf-8">
$('a#light, a#dark').click(function(){
$('style').remove();
$.ajax({
url:'http://www.example.com/' + $this.attr('id') + '.css',
success:function(data){
$('<style></style>').appendTo('head').html(data);
}
})
})
</script>
Of course, you need to load jQuery first.
There's 2 ways that come immediately to mind.
1) Add a style tag to the page's head, ensuring that the style tag has a unique id. You can then set the innerHTML of that element. (somewhat messy)
2) Add a link tag to the page's head, also ensuring that it has a unique id. You set the type='text/css' and the rel='stylesheet' attributes. You the set the src of this link element to the appropriate css file.
Here's an example of each type. Just supply css files for theme3() and theme4() functions.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
var style = newEl('style');
style.setAttribute('id', 'dynCss');
document.head.appendChild(style);
var style2 = newEl('link');
style2.setAttribute('type', 'text/css');
style2.setAttribute('rel', 'stylesheet');
style2.setAttribute('id', 'dynCss2');
document.head.appendChild(style2);
}
function theme1()
{
var style = byId('dynCss');
style.innerHTML = "h1{color: red;}";
var style2 = byId('dynCss2');
style2.setAttribute('href', '');
}
function theme2()
{
var style = byId('dynCss');
style.innerHTML = "h1{color: blue;}";
var style2 = byId('dynCss2');
style2.setAttribute('href', '');
}
function theme3()
{
var style = byId('dynCss');
style.innerHTML = "";
var style2 = byId('dynCss2');
style2.setAttribute('href', 'style3.css');
}
function theme4()
{
var style = byId('dynCss');
style.innerHTML = "";
var style2 = byId('dynCss2');
style2.setAttribute('href', 'style4.css');
}
</script>
<style>
</style>
</head>
<body>
<h1>This is the heading</h1>
<input type='button' onclick='theme1();' value='Theme 1'/>
<input type='button' onclick='theme2();' value='Theme 2'/>
<input type='button' onclick='theme3();' value='Theme 3'/>
<input type='button' onclick='theme4();' value='Theme 4'/>
</body>
</html>

Add stylesheet to Head using javascript in body

I'm working with a CMS that prevents us from editing the head section. I need to add css stylesheet to the site, right after the tag. Is there a way to do this with JS, where I can add a script to the bottom of the page (I have access to add script right before the tag) that would then inject the stylesheet into the head section?
Update: According to specs, the link element is not allowed in the body. However, most browsers will still render it just fine. So, to answer the questions in the comments - one really has to add link to the head of the page and not the body.
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}');
Or a little bit easier with jquery
function addCss(fileName) {
var link = $("<link />",{
rel: "stylesheet",
type: "text/css",
href: fileName
})
$('head').append(link);
}
addCss("{my-url}");
Original answer:
You don't need necessarily add it to the head, just add it to the end of body tag.
$('body').append('<link rel="stylesheet" type="text/css" href="{url}">')
as Juan Mendes mentioned, you can insert stylesheet to the head instead
$('head').append('<link rel="stylesheet" type="text/css" href="{url}">')
And the same without jQuery (see code above)
This will do what you want in an intelligent way. Also using pure JS.
function loadStyle(href, callback){
// avoid duplicates
for(var i = 0; i < document.styleSheets.length; i++){
if(document.styleSheets[i].href == href){
return;
}
}
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = href;
if (callback) { link.onload = function() { callback() } }
head.appendChild(link);
}
I've modified Eddie's function to remove or toggle the stylesheet on or off. It will also return the current state of the stylesheet. This is useful for example, if you want to have a toggle button on your website for vision-impaired users and need to save their preference in a cookie.
function toggleStylesheet( href, onoff ){
var existingNode=0 //get existing stylesheet node if it already exists:
for(var i = 0; i < document.styleSheets.length; i++){
if( document.styleSheets[i].href && document.styleSheets[i].href.indexOf(href)>-1 ) existingNode = document.styleSheets[i].ownerNode
}
if(onoff == undefined) onoff = !existingNode //toggle on or off if undefined
if(onoff){ //TURN ON:
if(existingNode) return onoff //already exists so cancel now
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = href;
document.getElementsByTagName('head')[0].appendChild(link);
}else{ //TURN OFF:
if(existingNode) existingNode.parentNode.removeChild(existingNode)
}
return onoff
}
Sample usage:
toggleStylesheet('myStyle.css') //toggle myStyle.css on or off
toggleStylesheet('myStyle.css',1) //add myStyle.css
toggleStylesheet('myStyle.css',0) //remove myStyle.css
You can use pure javascript and still elegance in the modern browser.
const range = document.createRange()
const frag = range.createContextualFragment(`THE CONTENT IS THE SAME AS THE HTML.`)
document.querySelector("YOUR-NODE").append(frag)
It's very easy to add any HTML code.
Document
createRange
createContextualFragment
Example 1
Add the style on the head by javascript.
<head></head><body><button class="hover-danger">Hello World</button></body>
<script>
const range = document.createRange()
const frag = range.createContextualFragment(`
<style>
.hover-danger:hover{
background-color: red;
font-weight: 900
}
</style>
`
)
document.querySelector("head").append(frag)
</script>
Example 2
Import CSS, JS, and modify the existing stylesheet.
<head></head>
<body><button class="btn btn-primary hover-danger">Hello world</button></body>
<script>
const range = document.createRange()
const frag = range.createContextualFragment(`
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"/>
`)
document.querySelector("head").append(frag)
window.onload = () => {
// 👇 If you don't want to import the new source, you can consider adding the data to exists source.
const nodeLink = document.querySelector(`link[href^="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"]`) // ^: match begin with my input
if (nodeLink) { // !== null
const stylesheet = nodeLink.sheet
const myCSS = `
background-color:red;
font-weight: 900;
`
stylesheet.insertRule(`.hover-danger:hover{ ${myCSS} }`, stylesheet.cssRules.length)
}
}
</script>
📙 You must have permission to modify the CSS directly
If you get the error:
Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules,
then you can reference: https://stackoverflow.com/a/49994161/9935654
Here is a simple one-liner to add a stylesheet:
document.head.insertAdjacentHTML('beforeend', `<link typs="text/css" rel="stylesheet" href="<Source URL>">`);

add javascripts and css files dynamicly to html using javascript

I am building a javascript widget and i need to add my widget css and js files dynamicly to the client page.
I am doing this for now:
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', 'css path');
document.getElementById('test').appendChild(css);
alert(document.getElementById('test').innerHTML);
But it does not add the element to the dom.
The alert shows correctly.
What i am missing?
EDIT1:
Here is the updated code: (note that this is only a test page).
<html>
<head>
</head>
<body>
<div id="test">
test
</div>
<script type="text/javascript">
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute("type", "text/css");
css.setAttribute('href', 'path');
var header = document.getElementsByTagName("head")[0];
header.appendChild(css);
alert(header.innerHTML);
</script>
</body>
</html>
header.InnerHtml appears correct but nothing is added to the page.
have you tried to append the css into the <head> section ?
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', 'css path');
document.getElementsByTagName('head')[0].appendChild(css);
I think you need to attach it to the of your html, not simply the document:
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute("type", "text/css");
css.setAttribute('href', 'css path');
var header = document.getElementsByTagName("head")[0];
header.appendChild(css);
Hope this helps :)

Categories

Resources