Consider the script..
<html>
<head>
<script type="text/javascript">
document.write('TEST');
</script>
</head>
<body>
Some body content ...
</body>
</html>
This works fine and the word 'TEST' is added to the <body>
But when
<script type="text/javascript">
window.onload = function(){
document.write('TEST');
}
</script>
is used, then the body content is fully replaced by the word 'TEST' i.e, the old body contents are removed and ONLY the word 'TEST' is added.
This happens only when document.write is called within window.onload function
I tried this in chrome. Is there any mistake made by me ? any suggestions ?
document.write() is unstable if you use it after the document has finished being parsed and is closed. The behaviour is unpredictable cross-browser and you should not use it at all. Manipulate the DOM using innerHTML or createElement/createTextNode instead.
From the Mozilla documentation:
Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call. Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page. The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.
If the document.write() call is embedded directly in the HTML code, then it will not call document.open().
The equivalent DOM code would be:
window.onload = function(){
var tNode = document.createTextNode("TEST");
document.body.appendChild(tNode);
}
in the first case the word is not written in the body .. it is written in the head
the first one works because the document is still open for writting.. once it has completed (DOM loaded) the document is closed, and by attempting to write to it you replace it ..
When document is full loaded, any further call to document.write() will override document content. You must use document.close() before calling document.write() to avoid overwriting.
First create an element, for example a div, than add content to the div with window.onload event.
document.write('<div id="afterpostcontent"><\/div>');
window.onload = function()
{
document.getElementById('afterpostcontent').innerHTML = '<span>TEST<\/span>';
}
You can create an external JavaScript file with this content and just call it anywhere, for example:
<script src="afterpostcontentcode.js"></script>
Related
I have this js code:
var id = document.getElementById("myDiv").getAttribute("data-id");
et="Your Message Here";
el="http://x2.xclicks.net/sc/out.php?s="+id+""
sl=new Array();
sn=new Array();
a="</a>"; af="<a target='_blank'";
function dw(n) {document.write(n,"\n");}
function showLink(n,s,b){
if(!s) {s='anc'}
if(!b) {b=''}
else {b="&b="+b}
ast = af+" class='"+s+"' href='"+el;
n = n-1;
if(sl[n]&&sl[n]!="") {
dw(ast+"&o="+sl[n]+b+"'>"+sn[n]+a)
} else {
dw(ast+b+"'>"+et+a)
}
}
Which I load in my header.php like this:
<script type="text/javascript" src="<? bloginfo('template_url'); ?>/js/trf.js"></script>
The problem is that although this is correct:
var id = document.getElementById("myDiv").getAttribute("data-id");
I get this error:
getElementById() is null or not an object
Ady Ideas why?
Do I need to declare a document ready or something?
Do I need to declare a document ready or something?
Yes, exactly. Before the document is ready (ie all tags are parsed to DOM elements), you won't be able to get elements by id. This would only work for elements above your script tag, which are already parsed. Moving the script inclusion from <head> before the end of </body> would help. Alternatively you'll need to use one of the various DOMContentLoaded or onload events, which unfortunately are not cross-browser supported. I recommend to search for a good snippet or use a library.
Assuming you're loading that script in the <head> of your document, you are trying to get an element by ID when that element is not yet loaded into the DOM.
You will need to wait for your document to be ready (via onDOMContentLoaded, window.onload, or any other way of deferring until rendering is complete) in order to access that element by ID.
I would try wrapping it in a $(document).ready. More than likely you're just trying to access it before the DOM is ready
You're loading the script in the header, which means that the script is being loaded before the rest of the document. Inside the script, you're calling document.getElementById straight away, and since the rest of the document hasn't finished loading the chances are extremely high the element you're after won't exist yet.
You need to delay running that part of the script until the document is fully loaded. Wrap that part of the script in a function, and call it during the body.onload event.
As an example (there are other ways to achieve the same result):
window.document.onload = function(e){
var id = document.getElementById("myDiv").getAttribute("data-id");
// Now you have the id and can do whatever you want with it.
}
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
<html>
<head>
<title>Test javascript</title>
<script type="text/javascript">
var e = document.getElementById("db_info");
e.innerHTML='Found you';
</script>
</head>
<body>
<div id="content">
<div id="tables">
</div>
<div id="db_info">
</div>
</div>
</body>
</html>
If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?
The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:
window.onload = function () {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
};
Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.
Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.
How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,
window.onload = doStuff;
function doStuff() {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
}
The other alternative is to keep your <script...</script> just before the closing </body> tag.
Script is called before element exists.
You should try one of the following:
wrap code into a function and use a body onload event to call it.
put script at the end of document
use defer attribute into script tag declaration
The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.
Run the code either in onload event, either just before you close body tag.
You try to find an element wich is not there at the moment you do it.
I want to ask a question about the Javascript’s onload.
I’m writing a JSP page with the code <%# include file ="body.jsp". The included body.jsp contains:
<table onload="function()">
This should load the javascript function, but it doesn't appear to have any effect on the page. Is onload only usable on the body tag?
Onload can only be used for <body>, <img>, <script>, <iframe> tags, because it tells you when an external resource (image, script, frame) or the whole page (body) has been loaded
Since HTML5 these can also fire a load event: <link>, <style>, <input type=image>, <object>
Support for these can still be a hit or miss though (e.g. older Android browsers)
Why not just include it via a <script tag>?
Inside your .jsp file
<script>
window.onload = function() {
alert("Hello!");
}
// or to execute some function
window.onload = myFunction; //notice no parenthesis
</script>
As the other guys already stated the onLoad event will not fire on a table. What you can do ist attaching the onLoad-handler to the body element (which will then fire, when the page is loaded) and manipulate the table by for example assigning an id to the table.
<body onload="function() { var table = document.getElementById("table-id"); ... }">
<table id="table-id"></table>
</body>
Are you using some javascript framework?
"onLoad" may be used on body- and frameset-tags.
To see some action you may use:
<body onload="function(){alert('This is an action!')}">
The easiest way i find is to use an external javascript file and jquery.
// Variables and functions you want to declare
var socket = io.connect();
// .....
// Function you want to run on load
$(function() {
$('#submit').click(function() {addUser();});
// ... any other functions you want to run on load
});
This is a code snippet from something that i was working on. The variable is declared before the code runs (It creates a web socket).
Then there is the jquery document selector ($) which runs on load and calls the init function to modify my html. I use it to call an anonymous function which runs right away.
You can throw a <script> tag right after your table with code. Once it gets to the script tag it would mean that the DOM for the table element above it has been loaded and can now be accessed in your script below it.
Note: The following below isn't applicable to the question but rather the other answers being given.
I recommend using the addEventListener function in javascript for adding the event. This makes sure that you are not overwriting or going to be overwritten by anyone else wanting to listen to the event.
Example
var iframe = document.getElementsByTagName('iframe')[0];
iframe.addEventListener('load', function(event){ console.log("iframe Loaded", event); })
I'm writing a webpage that relies on an external javascript file (that I have no control of), which returns data by using document.write's. Is there any way to dynamically call the function without it overwriting the whole document? Here's the most concise code I can think of:
<html>
<head>
<script type="text/javascript">
function horriblefunction () {
document.write("new text");
}
</script>
</head>
<body>
Starting Text...
<div id="pleasewriteinme"></div>
Other text...
<button onclick="horriblefunction();">Click</button>
</body>
</html>
The idea beginning that without altering "horriblefunction()" (as it's external) the new text could be placed in the div instead of overwriting the page. Is this possible or does the function have to be called inside the div as the page is created?
Thanks for you help
The only way to use document.write after the page has finished rendering is to temporarily replace the function with one of your own making that will shove the content into a div. E.g.
function horriblefunction() {
var old_dw = document.write;
document.write = function(text) {
document.getElementById( 'some_div' ).innerHTML = text;
}
// now call your external JS function that uses document.write
document.write = old_dw;
}
This will work as long as the external JS is already loaded and you're just calling a function. If you need to load the JS (say, by inserting a new <script> tag into the DOM) remember that that operation is asynchronous, and you'll need to watch the DOM to know when it's safe to restore the old version of document.write.
Try using dynamic script loading from http://bezen.org/javascript/index.html
bezen.domwrite.js - Captures document.write and writeln for the safe loading of external scripts after page load.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
I've been using document.GetElementById() successfully but from some time on I can't make it work again.
look at the following Code:
<html>
<head>
<title>no title</title>
<script type="text/javascript">
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
</script>
</head>
<body>
<div id="ThisWillBeNull"></div>
</body>
</html>
I am getting document.getElementById("parsedOutput") is null all the time now.
It doesn't matter if I use Firefox or Chrome, or which extensions I have enabled, or what headers I use for the HTML, it's always null and I can't find what could be wrong.
You can use the script tag like this:
<script defer>
// your JavaScript code goes here
</script>
The JavaScript will apply to all elements after everything is loaded.
Try this:
<script type="text/javascript">
window.onload = function() {
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
}
</script>
Without window.onload your script is never invoked. Javascript is an event based language so without an explicit event like onload, onclick, onmouseover, the scripts are not run.
<script type="text/javascript">
window.onload = function(){
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
}
</script>
Onload event:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
https://developer.mozilla.org/en/DOM/window.onload
Timing.
The document isn't ready, when you're getting the element.
You have to wait until the document is ready, before retrieving the element.
The browser is going to execute that script as soon as it finds it. At that point, the rest of the document hasn't loaded yet — there isn't any element with that id yet. If you run that code after that part of the document is loaded, it will work fine.
<script type="text/javascript">
window.onload += function() {
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
}
</script>
Use += to assign more eventHandlers to onload event of document.