I am trying to add a stylesheet only on the condition that the browser is either Chrome or Opera. I have the following control flow using the YUI library:
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.write("<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>");
}
Here is the conditionally attached css file, style_ticket_printing_header.css
#page
{
size: auto;
margin: 0mm;
}
Here is the full HTML:
https://gist.github.com/ebbnormal/b1cff9d45914bc2f63a4
When I run the page in Chrome, none of the <div>s that are defined within the <body> tag are rendered or are displayed within the DOM.
What is particularly confusing is that, when this CSS is loaded in the normal way (by simply referencing it via a <link> tag in the <head> of the page, all of the DOM are loaded perfectly.
And finally I know that it successfully renders the condition of seeing it is chrome as I formerly had an alert message in the body of the if block which successfully executed.
document.write() for adding a stylesheet causes document to be blank
Right. When you use document.write after the main page parsing is complete, it implicitly does a document.open, which wipes out the page.
Instead, use createElement and appendChild:
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
var link = document.createElement('link');
link.rel = "stylesheet";
link.media = "print";
link.type = "text/css";
link.href = "../../../css/style_ticket_printing_header.css";
document.querySelector("head").appendChild(link);
}
Or if you really like to use HTML: :-)
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.querySelector("head").insertAdjacentHTML(
"beforeend",
"<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>"
);
}
(Both of the above assume you have a head element, which you presumably do; it's required in a well-formed HTML document, either explicitly or because the browser adds it for you [but explicit is best].)
About querySelector: It finds the first element that matches a CSS selector. It's supported by all modern browsers, and also IE8. (There's also querySelectorAll, which finds a list of matching elements.)
Inside of your <head> tag in html file,
<SCRIPT LANGUAGE="JavaScript">
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.write("<LI" + "NK rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>");
}
</SCRIPT>
it may work.
Assuming you want to add the stylesheet into the head, take a look at this: Append some HTML into the HEAD tag?
The basic idea is to use
var newElement = document.createElement('element')
and
newElement.setAttribute('attr', 'val')
This will work (as originally suggested by users1100's answer on SharePoint.SE):
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.com/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
Related
I am using document.write in a function to give different CSS to user's based on their choosing.
function blue() {
document.write('<link rel="stylesheet" type="text/css" href="http://ilam.irib.ir/documents/697970/237563314/blue.css" />');
}
I am calling the function from an anchor tag.
function color2(){
document.getElementById("navigation").innerHTML +='<a class="myButton" onclick="blue()" background-color:"#05c8f2";></a>';
}
As you can guess, when the link is clicked, the page clears out and I get a blank page.
Is there any way to fix this problem? I don't want to stop page refreshing, I'm just trying to fix the problem in any way possible!
Note: don't ask why I'm adding code using JavaScript, and not directly into HTML code. This site is a large scale system and we just have access to JavaScript and CSS. So this is all we can do to edit our pages.
document.write rewrites the body , as a result the only thing in your document remains is the css file you added and hence it is blank.
View this
Code from above link :-
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.com/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
Instead of rewriting while dom , we append the link element inside head tag
I have another site running inside a webpage as an iframe. However it's not displaying the favicon. I think it's not possible but just wanted to double confirm if someone knows of a way.
May be something like this in your child page i.e. page inside iFrame :
(function() {
var link = parent.document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = 'http://www.stackoverflow.com/favicon.ico';
parent.document.getElementsByTagName('head')[0].appendChild(link);
}());
You can set a favicon by modifying the HTML, i.e. by adding:
<link rel="shortcut icon" type="image/png" href="/favicon.png"/>
to the <head> (or changing the existent link).
You can also access DOM of the top document if both the top document and the iframe are on the same domain.
Example:
master = window.parent.document;
head = master.getElementsByTagName("head")[0];
favicon = master.createElement("link");
favicon.rel = "shortcut icon";
favicon.type = "image/png";
favicon.href = "//cdn.sstatic.net/stackoverflow/img/favicon.ico?v=038622610830";
head.appendChild(favicon);
sets the icon of the page to Stack Overflow favicon.
I have created a bookmarklet that executes the below code, adding css styling to the page. It works on all tried sites in Chrome and Firefox, but fails for some sites on IE. It's always the same sites that fail.
The fourth line fails with "Unexpected call to method or property access" for SOME sites, only on IE.
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(""));
head.appendChild(style);
Two sites that fail on IE 10:
http://www.momswhothink.com/cake-recipes/banana-cake-recipe.html
http://www.bakerella.com/
I think your problem is this line:
style.appendChild(document.createTextNode(""));
Here you are inserting a Text Node into a Style element, which according to the HTML specification is not allowed, unless you specify a scoped attribute on the style.
Check the specification of style here (Text Node is flow content).
You can find good ways to create the style element in a crossbrowser way here.
probably because you forgot to add document.ready()
Using jquery
$(document).ready(function(){
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(""));
head.appendChild(style);
});
Using javascript
Try wrapping your javascript in an onload function. So first add:
<body onload="load()">
function load() {
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(""));
head.appendChild(style);
}
I'm not sure why you're getting that error in IE10... I know in IE<9 an error is thrown if you try to modify the innerHTML of a <style> tag. It's still doable, you just have to do a bit of a workaround. For example (using jQuery):
var customCSS = "body { color: red; }";
var customStyle = $('<style type="text/css" />');
try {
$(customStyle).html(customCSS); // Good browsers
} catch(error) {
$(customStyle)[0].styleSheet.cssText = customCSS; // IE < 9
}
$(customStyle).appendTo('head');
Hope this helps.
Do you really have to dynamically add the style section to the page? What about adding the attribute, itself, on the fly, like this:
$(document).ready( function() {
$('[id="yourObjID"]').css('yourAttribute','itsvalue');
});
Adding the style section dynamically, rather than the attribute, seems like way overkill, to me.
I want to append element To head of an Iframe (fancybox)
there is a strange problem : when I use Firefox to Breakpoint on line of code that append element to Head it works correctly but when I run site normally without firebug it does not work;
I am using fancybox 1.3.4 and the code run in onComplete event
var cssLink = document.createElement("link")
cssLink.href = "/themes/furniture/css/test.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
var f123= document.getElementById('fancybox-frame');
var d123= f123.contentDocument || f123.contentWindow.document;
d123.head.appendChild(cssLink);
UPDATE
I also try this code
var $head = $("#fancybox-frame").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "/themes/furniture/css/test.css", type: "text/css" } ));
but it does not work either
Tnx
Well, it seems to be a racing condition indeed (as pointed out by olsn in his comment) between loading the iframe and finding elements inside of it, which fails if the second occurs first ;)
As a workaround, you could use the .load() method to wait for the iframe to be completely loaded before trying to append the stylesheet to the <head> section.
This code should do the trick :
$(document).ready(function () {
$(".fancybox").fancybox({
"type": "iframe",
"onComplete": function () {
var $style = '<link rel="stylesheet" href="/themes/furniture/css/test.css" type="text/css" />';
$("#fancybox-frame").load(function () {
$(this).contents().find("head").append($style);
});
}
});
});
Note : this is for fancybox v1.3.4. Fortunately v2.x includes more flexible public methods than v1.3.4 to circumvent this issue, like afterLoad and beforeShow
Also notice that setTimeout() will work too, but it renders oddly.
I'm working with a CMS, which prevents editing HTML source for <head> element.
For example I want to add the following above the <title> tag:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
You can select it and add to it as normal:
$('head').append('<link />');
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
const link = document.createElement('link');
link.href = 'href';
link.rel = 'rel';
document.getElementsByTagName('head')[0].appendChild(link);
jQuery
$('head').append( ... );
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
You can use innerHTML to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.
In the latest browsers (IE9+) you can also use document.head:
Example:
var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';
document.head.appendChild(favicon);
Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().
Try a javascript pure:
Library JS:
appendHtml = function(element, html) {
var div = document.createElement('div');
div.innerHTML = html;
while (div.children.length > 0) {
element.appendChild(div.children[0]);
}
}
Type:
appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');
or jQuery:
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));
With jquery you have other option:
$('head').html($('head').html() + '...');
anyway it is working. JavaScript option others said, thats correct too.