Where should scripts be placed when referring to the DOM? - javascript

If you have something like the code below, it is impossible to access any node type below the head tag. I am guessing the reason is the JavaScript code executed before the rest of the document was created. But is there a way to access these nodes from the head tag. I want to access them from the head tag because I like my JavaScript code to be in one location if possible. I know jquery uses $(document).ready(). Is there something similar to that?
<!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>
<script type="text/javascript">
var div = document.getElementById('myDiv')
alert(div)
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id='myDiv'></div>
</body>
</html>

The simplest analog to jQuery's $(document).ready() is window.onload:
<!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>
<script type="text/javascript">
window.onload = function(){
var div = document.getElementById('myDiv')
alert(div)
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id='myDiv'></div>
</body>
</html>
It is not as good because it will wait until all images are downloaded before it fires. If you must have the equivalent, you could use a microlib such as this one.

"I like my JavaScript code to be in one location if possible"
Yes: An external js file. It is bad practice to write js in the head. In the same way that writing styles in the head is poor. Hopefully you are using jquery for more than just the ready event, but it is an invaluable initializer even if you aren't. Write your js in a separate file, hopefully in some type of a container so you don't clutter the global namespace, and initialize it with $(document).ready();

You must wait for the 'onload' DOM event. jquery $(document).ready() is a wrapper for setting event handlers for onload.
Without jQuery you might try:
<!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>
<script type="text/javascript">
function do_onload() {
var div = document.getElementById('myDiv')
alert(div)
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload='do_onload()'>
<div id='myDiv'>I am here</div>
</body>
</html>

Well as a general rule i tend to put all inline js at the end of the document anyway, only externals do i usually put in the head. However, you can use the same methods jquery uses. I dunno exactly what the jq source looks like but something like this should work (untested):
window.onDomReady = function (fn) {
if(document.addEventListener) {
document.addEventListener("DOMContentLoaded", func, false);
} else {
document.onreadystatechange = function(func){
if(document.readyState == "interactive") {
fn(func);
}
}
}
};
And then you would use it like:
window.onDomReady(function(){
// do your stuff
});
I dunno if thats completely cross browser compatible either... that would be on of the benefits of using something like jQuery instead of writing your own.

Related

script tag doesn't work in head tag

script tag doesnt execute if i put it in head tag but works fine if i put it in body tag ..can anybody tell me the reason behind this?? here's my code
<!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 content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
</body>
</html>
That's because HTML is parsed from top to bottom. That means that when you try to get the element demo it is not yet created.
To make it work in the head tag you should add a listener that will fire when the page is fully loaded.
document.addEventListener("DOMContentLoaded", function() {
// Here the DOM elements are loaded, and you can get them with .getElementById.
document.getElementById("demo").innerHTML = Date();
});
The <head> is for including other files and libraries and such (you can also include them in the body). But if you want to actually write JS code to manipulate the body, you have to place it in the body.

Using $(tag).load() successfully in jQuery

Hi I'm trying to use jQuery to load an html document into an existing html document.
I've tried using the code below, but the text doesn't load.
I'm not sure why. Could someone point me towards what I'm doing wrong please?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">$("#test").load("test.txt")</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
Try on DOM ready like
<script type="text/javascript">
$(document).ready(function(){
$("#test").load("test.txt");
});
</script>
And you also forgotted ending ;.You can also try like
$(function(){
$("#test").load("test.txt");
});
You need to add it in dom ready
jQuery(function($){
$("#test").load("test.txt")
})
The problem was when your script is executed the element with id test was not yes added to the dom so the selector $("#test") would return zero elements

function in ajax loaded content run after removal also

My html page
<!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><script src="js/jquery.js"></script>
<script>$(function(){
$("button:first").click(function(){
$("#aja").load("ajax.html");});
$("button:last").click(function(){
$("#aja").remove();});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<button>Load page</button><button id="rem">Remove ajax content</button>
<div id="aja"></div>
</body>
</html>
and ajax.html code
<body>
<script>$(function(){
cool();});
function cool(){
$("button:last").after("Hello");
setTimeout("cool()",10000);}
</script>
</body>
Now when i load ajax.html it cool() function runs and keeps on adding hello to last button .The problem is when i remove the ajax loaded content with second button,cool() function which is removed keeps on running .But i want the cool function to stop after removal of ajax content
Checking on existence of #aja block may help:
function cool() {
if ($("#aja").length == 0) return;
$("button:last").after("Hello");
setTimeout("cool()", 10000);
}
You want to use clear timeout
http://www.w3schools.com/jsref/met_win_cleartimeout.asp

Getting Render Page Source with Javascript

I have following 2 files as below:
<!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>Untitled Document</title>
</head>
<script>
function init(){
document.getElementById("mytest").innerHTML= "Results after rendering...";
}
</script>
<body onload="init();"><div id="mytest">OK</div>
</body>
</html>
The second page usually give the alert popup all source code of first page.
<!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>Untitled Document</title>
</head>
<script>
xmlhttp.open("GET", "test.html",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send(null)
</script>
<body>
</body>
</html>
All I want to do is I would like to get ONLY source code after rendering. How can get all code after rendering instead of getting all original code. So i can read < div id="mytest">Results after rendering...< / div> when I try with XMLHTTP. How can I do how to get the code which are already render for page, I want only with classic Javascript or DOM, I don't want with Jquery, JSON, Mootool at all. thanks in advance.
Instead of loading the page with ajax, use your browser's iframe support to your advantage.
Change the second file that alerts the HTML source to something like this:
<!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>Untitled Document</title>
</head>
<script>
function displayAlert()
{
alert(document.getElementById('iframe').contentDocument.body.innerHTML);
}
</script>
<body onload="displayAlert()">
<iframe src="test.html" id="iframe" style="display:none;"></iframe>
</body>
</html>
This will load test.html in an invisible iframe. Your browser will automatically render test.html inside the iframe and will call displayAlert() when it is done. displayAlert() will grab the the source code inside the iframe and alert it. However, this solution will only work if test.html is on the same server as the script above. If test.html is on a completely different server, this solution will not work because the permission to access the iframe will be denied. If this is the case, I can let you know of another solution that will bypass this.
I'm not sure I know what you're really asking, but why not just get:
alert(document.body.innerHTML);
to get the actual rendered body HTML with any changes that have been made by scripts upon loading.
Note: even unmodified parts of innerHTML will not always compare exactly to the original source HTML because in some cases browsers are reconstituting the innerHTML from some other parsed data form so attributes may not have the same quoting or be in the same order and capitalization may not be the same.

javascript document.innerHTML set content of whole document

How can I set the innerHTML, or the whole content of an HTML document using javascript?
For example my document would look like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-language" content="en"/>
<title>Webpage Generator</title>
<script type="text/javascript">
var newDocument = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" \n\t"http://www.w3.org/TR/html4/loose.dtd">\n<html>\n<head>\n\t<title>Greetings!</title>\n</head>\n<body>\n\t<p>Howdy!</p>\n</body>\n</html>";
document.innerHTML = newDocument;
</script>
</head>
<body>
</body>
</html>
But the browser would load the following HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Greetings!</title>
</head>
<body>
<p>Howdy!</p>
</body>
</html>
If you don't want to use innerHTML you could use document.write(newDocument);.
If the document hasn't completely loaded, you'll need to put document.open() as well (thanks bažmegakapa).
document.innerHTML is new in HTML5 and isn’t supported in all browsers.
document.documentElement refers to the root element of your document, which in this case is the <html> element.
So, you could set document.documentElement.innerHTML. Note that since the DOCTYPE falls outside of that, so there’s no need to include that in the innerHTML.
Example (try running this in your browser’s JS console):
document.documentElement.innerHTML = '<title>Test</title><p>LOLWAT';
Update: document.innerHTML moved from the HTML specification to the DOM Parsing and Serialization spec, and later got removed. The suggested alternative is to use DOMParser:
var doc = (new DOMParser).parseFromString('<!doctype html><title>wat</title>', 'text/html');
Unfortunately, at the time of writing, most browsers don’t support this yet for HTML.
Use this code (after current document has been loaded) :
document.open("text/html", "replace");
document.write(htmlCode); // htmlCode is the variable you called newDocument
document.close();
Live exemple here :
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_open
hope this help ;)
Simple:
document.body.parentElement.innerHTML = '<html><body><div>Your code</div></body></html>';
Note that it will not interpret js code embedded in your html code.

Categories

Resources