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.
Related
This question already has answers here:
Why doesn't document.addEventListener('load', function) work in a greasemonkey script?
(6 answers)
Why "load event not working on addEventListener()"?
(3 answers)
Closed 1 year ago.
i am trying to execute the document.addEventListener() but it is not working why ?
<html>
<head>
<title>javascript</title>
<link rel="stylesheet" href="C:\Users\SUDARSHAN\Desktop\html_UI\eventstyle.css">
</head>
<body>
<p id="p1">Welcome</p>
</body>
<script>
function f1() {
document.getElementById("p1").style.fontSize="50px";
}
document.addEventListener("load",f1);
console.log("hello");
</script>
</html>
You must append a load listener to window instead of document.
window.addEventListener("load",f1);
That being said, you cannot have a script element as a child of the html element, it must be in the head or body (which are the only allowed children of html). Always make sure your HTML is valid at all times; invalid HTML puts you in unspecified territory and tends to make things unpredictable (even if things seem to work).
Flaws in above code.
Always make sure the html tag documented correctly. For ref https://www.w3schools.com/tags/tag_doctype.asp
load event depends on window. In above code, you added the listener for document.
You can try following:
document.addEventListener('DOMContentLoaded', f1);
There are two events which are related to loading and unloading of the Document
DOMContentLoaded
readystatechange
Refer this page for windows events
https://developer.mozilla.org/en-US/docs/Web/API/Document#load_unload_events
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>
So i have this empty page,
<html>
<head>
<title>JS</title>
<script type="text/javascript">
var container = document.getElementById("container");
console.log(container);
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
and for some reason console.log returns "null" instead of div object. But when i put code onto some website like jsfiddle, it works.
How do i fix this, is it a common problem?
JSFiddle may not mimic DOM loading correctly. The problem with your example is your JavaScript is executed before the DOM is completely loaded. The DOM is loaded top-down, so when your JavaScript is executed, the container div doesn't exist in the DOM yet.
You can move your script block after your div, that's a quick way to resolve the issue. Alternatively, you can listen for an event for when the DOM is loaded, then execute your code. This StackOverflow question demonstrates how to do that.
This question is so basic, I'm certain in must be a duplicate of something, even though I've looked for something similar.
My question is basically: Where is the best place to initially register event handlers for HTML elements?
The easiest way to register an event handler is obviously to just do it inline:
<div id = "mybutton" onclick = "doSomething()">Click me</div>
But this goes against the overwhelming march towards separation of logic and content in modern web development. So, in 2012, all logic/behavior is supposed to be done in pure Javascript code. That's great, and it leads to more maintainable code. But you still need some initial hook that hooks up your HTML elements with your Javascript code.
Usually, I just do something like:
<body onload = "registerAllEventHandlers()">
But... that's still "cheating", isn't it - because we're still using inline Javascript here. But what other options do we have? We can't do it in a <script> tag in the <head> section, because at that point we can't access the DOM since the page hasn't loaded yet:
<head>
<script type = "text/javascript">
var myButton = document.getElementById("mybutton"); // myButton is null!
</script>
</head>
Do we place a <script> tag at the bottom of the page or something? Like:
<html>
<body>
...
...
<script type = "text/javascript">
registerAllEventHandlers();
</script>
</body>
</html>
What is the best practice here?
You can use window.onload:
<script type = "text/javascript">
window.onload = registerAllEventHandlers;
</script>
Or if you use jquery:
$(registerAllEventHandlers);
Using onload works because it registers onload event immediately but fires it when DOM is ready.
I had a similar answer to this but was about JavaScript in general. But the idea is still the same - load scripts before closing the body.
Take advantage of libraries that abstract the window.onload and the DOM ready event. That way, you can load the scripts as soon as the DOM is ready.
Personally, I have no problems with adding onlclick="doSomething();" to elements. No logic, just a function call.
All logic is where it should be: in the function defined in the HEAD or a separate file.
Tell me what the difference is when you add href="somepage.html" or even href="somepage.html#someanchor" to an A tag.
You should register your event handlers as soon as the DOM is ready. Detecting this across all browsers hasn't always been easy, although with the notable exception of IE 8 (and earlier) most widely used browsers now support the DOMContentLoaded event (thanks to gengkev for pointing that out in the comments).
This is essentially equivalent to calling your registerAllEventHandlers function at the end of your body, but it has the advantage that you don't need to add any JavaScript to your HTML.
It is significantly better than using window.onload because that isn't executed until all of the page's assets (images, CSS etc.) have loaded.
If you're using one of the major JavaScript frameworks, then you can very easily detect when the DOM is ready, even in older versions of IE. With jQuery you would use the ready event:
jQuery(document).ready(function () {
// Your initialisation code here
});
Or the shorthand:
jQuery(function() { … });
With Prototype you would use the dom:loaded event:
document.observe("dom:loaded", function() {
// Your initialisation code here
});
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.