jQuery.html() removes scripts and styles - javascript

Is there a way to use jQuery.html() and not loose the scripts and styles? or any other non-jQuery way?
I'm trying to output the full HTML of the page the user is on. Is this even possible?

jQuery.html() removes scripts and styles
That isn't my experience (see below). In practice, you have to be aware that what you get back by querying the DOM for HTML strings is always going to be the interpreted HTML, not the original, and there will be quirks (for instance, on IE all the HTML tag names are IN UPPER CASE). This is because jQuery's html function relies on the browser's innerHTML property, which varies slightly browser to browser. But the demo below includes both style and script tags on Chrome 4, IE7, and Firefox 3.6; I haven't tried others, but I would expect them to be okay.
If you want to get the content of externally-linked pages as well as the inline content, you will naturally have to parse the result and follow the src (on scripts), href (on links that have rel = "stylesheet"), etc...
Demo:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
(function() {
$(document).ready(pageInit);
function pageInit() {
$('#btnGo').click(go);
}
function go() {
alert($('html').html());
}
})();
</script>
</head>
<body>
<input type='button' id='btnGo' value='Go'>
</body>
</html>

I see 2 scenarios here
you use jQuery.html(yourHTML) to overwrite the entire html of the page, so even the script tags were overwritten...
you use jQuery.html() to retrieve the entire document html. if this is the case you need tu ensure that the element on which .html() function is used, is the entire html... as T.J. Crowder suggested $('html').html()

Related

How to suppress or exclude CSS file from shiny header without reloading app [duplicate]

I don't want to use styles from style.css, so I decided to remove style.css from DOM. This work just fine in Firefox and IE8, but not in IE6:
$("LINK[href='http://www.example.com/style.css']").remove();
Any other solution, with jQuery?
Here is example:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("link[href*='style.css']").remove();
});
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="content">...</div>
</body>
</html>
And here is CSS (style.css):
#content {
background-color:#333;
}
Only in IE #content is still dark. :(
Maybe is jQuery bug?
This is not a bug in jQuery, it is a bug (or possibly, a feature) of the IE rendering engine.
It seems this problem is being caused by the fact that Internet Explorer does not correctly re-render the page after removing the LINK element from the DOM.
In this particular case, the LINK tag is no longer present at the DOM, but IE still displays the CSS that has been loaded into memory.
A workaround / solution for this is to disable the stylesheet using the .disabled property like this:
// following code will disable the first stylesheet
// the actual DOM-reference to the element will not be removed;
// this is particularly useful since this allows you to enable it
// again at a later stage if you'd want to.
document.styleSheets[0].disabled = true;
EDIT in reply to your comment:
Or, if you want to remove it by the href use the following code:
var styleSheets = document.styleSheets;
var href = 'http://yoursite.com/foo/bar/baz.css';
for (var i = 0; i < styleSheets.length; i++) {
if (styleSheets[i].href == href) {
styleSheets[i].disabled = true;
break;
}
}
Perhaps it's something strange IE6 does to URL in the href attribute? Try something like:
$("LINK[href*='style.css']").remove();
(i.e. check whether the href value contains "style.css")
It's just a guess, however. If that doesn't work, I recommend checking the JQuery documentation closely on the subject of attribute selectors and the remove method.
Also keep in mind that it's also not impossible that it's in fact a bug. (IE6 in general causes lots of issues involving JavaScript and DOM manipulation, among other things.)
Topic's quite old, but You can only add ID to your link element, and delete it by element:
$("#id").remove();
Maybe using lowercase on the tag name?

How to render html from a external js file

This might be a dumb question but I have actually never done this and what I am trying is not working.
I have 2 files
test.html
test.js
I am linking the js as an external in test.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
In my js file I have something like this
document.appendChild('<div>testing</div>')
I also tried
document.getElementsByTagName('body').appendChild('<div>testing</div>')
What I am doing wrong? I just want to learn how to generate html from an external js file for a future project I am working on.
You should generally try to run scripts that depend on the page after the document has been parsed, not before - if you put the script in <head> and run it immediately, the <body> has not been created yet. Give your script tag the defer attribute so that it only runs after the document is fully parsed:
<script defer type="text/javascript" src="test.js"></script>
appendChild accepts an element as a parameter, not a string
You need to append to the body, not the document itself (Only one element on document allowed.)
If you want to append an HTML string, assign/concatenate to the .innerHTML property
Assigning to .innerHTML will corrupt existing references to elements inside, including listeners. In order to keep listeners active, use insertAdjacentHTML instead:
document.body.appendChild(document.createElement('div'))
.textContent = 'testing1';
// Another method:
document.body.innerHTML += '<div>testing2</div>';
// Another method:
document.body.insertAdjacentHTML('beforeend', '<div>testing3</div>');

Replace complete HTML document with HTML code containing inline scripts

I have the following code which works properly in chome
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
//<![CDATA[
!function (){
window.stop();
var html = '<!DOCTYPE html>\n<html>\n<head>\n <meta charset="utf-8">\n</head>\n<body>\n \<script>console.log("loaded");<\/script>\ntext\n</body>\n</html>';
document.documentElement.innerHTML = html;
}();
//]]>
</script>
</body>
</html>
It prints "loaded" in the console. The same code does not work by firefox, it does not run the script, just prints the text.
(If you are curious why I need this, you can find it here: https://stackoverflow.com/a/30933972/607033 )
I tried possible solutions like this: https://stackoverflow.com/a/20584396/607033 but they did not work. Any idea how to work this around?
Note: there are many scripts in the HTML, e.g. bootstrap, jquery, facebook, google, etc..., not just a single inline script.
I think there is no way in firefox to replace the complete HTML document with javascript without leaving the actual page. A workaround to reuse the original document and replace only the head and body tags:
$('html').html(html);
does this automatically: it strips out the HTML tags, injects the head and the body and loads the scripts.
ref: https://stackoverflow.com/a/1236372/607033

Stylesheet ignored when using body onload and document.write

I am messing around with JavaScript experimenting to get a feel for it and have already hit a problem. Here is my html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="testing.js"></script>
</head>
<body onload="writeLine()">
</body>
</html>
Here is the JavaScript testing.js:
function writeLine()
{
document.write("Hello World!")
}
Here is the style sheet styles.css:
html, body {
background-color: red;
}
So a very simple example, but I may have chose an awkward example, using on-load in a body tag. So the code above loads and runs the function, but the style sheet does nothing, unless I remove the script tags in the head. I have tried putting the script tags everywhere else, but nothing works. I have researched on-line how to properly link to JavaScript files, and have no found no clear solution, can anyone point out my error?
I have used JavaScript before, but I want a clear understanding from the beginning before I use it any longer
You cannot use document.write after the document is closed (which it will be when onload fires) without destroying the existing document (including links to stylesheets).
Instead, use DOM manipulation, which is covered by chapters 8 and 9 of the W3C JavaScript Core Skills.
Your problem is with the document.write() called in a wrong moment*. This method prints given text at current place in the page as was intended to work while the page still loads. Because you are calling it when the whole page was loaded, the results are unexpected (undefined?)
Instead you should manipulate the dom tree directly:
function writeLine() {
var text = document.createTextNode("Hello World!");
document.body.appendChild(text);
}
Actually in Opera browser I see red background for few milliseconds and then it goes back to white. Try commenting out document.write() - the background is as expected. Moreover you should include <script> tag at the end of body, but this won't solve your problem.
* to be honest, there is no good moment for calling document.write(), avoid it
In your particular example it doesn't matter where the script tag is added as the document.write command executes after the content is rendered, overwriting the existing content.
If you add an alert before overwriting the content you can see your page is red before it gets overwritten with Hello World.

css not being applied to document.write text

I'm writing text to a page using document.write for a Chrome extension, but the associated custom CSS isn't applied:
<!DOCTYPE html>
<html>
<head>
<title>TITLE GOES HERE</title>
<link rel="stylesheet" href="css/popup.css" type="text/css" />
</head>
<body>
<script type="text/javascript">
...
function showFolder(folder) {
console.debug('FOLDER: '+folder.title);
document.write('<p>'+folder.title+'<br></p>');
}
</script>
</body>
</html>
The CSS is simple, just for debugging:
p {
color: red;
}
I can get it to work if I put the stylesheet link inside the function showFolder, but that can't be the proper way to do it. I'm learning jscript/CSS on the fly, so the answer is probably something remedial. Is the problem in the jscript, the CSS or both?
Use innerHTML.
<div id="towrite"></div>
then you can write in it like this:
div=document.getElementById('towrite');
div.innerHTML = '<p>'+folder.title+'<br></p>';
If you run your document.write() before the page finishes loading (perhaps calling your showFolder call directly from a script on the page), then the text will be written into the document as you might expect.
However, if you call document.write after the page loads, as in an event handler, you will be writing an entirely new page. This is usually not what you want.
Instead, follow Zoltan's advice and set the innerHTML property of an empty div.
I'm not javascript expert... I mainly use jQuery.. but try this, kind of makes sense:
<!DOCTYPE html>
TITLE GOES HERE
<script type="text/javascript">
...
function showFolder(folder) {
console.debug('FOLDER: '+folder.title);
document.write('<p>'+folder.title+'<br></p>');
}
</script>
<link rel="stylesheet" href="css/popup.css" type="text/css" />
EDIT:
So the above didn't work, but I just thought about another solution. When are you actually calling the function? Try to put it in <body onLoad="functionnamehere()">
No idea if that works, but give it a try.

Categories