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.
Related
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>
I would like to globally redefine a createElement method, but unfortunately it only works in a main document, and is ignored in iframes. Let's take this example code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
old_createElement = document.createElement;
document.createElement = function(el_type) {
new_el = old_createElement.call(this, el_type);
new_el.style.color="red";
return new_el;
};
</script>
</head>
<body bgcolor="white">
<iframe id="iframe1"></iframe>
<script type="text/javascript">
window.setTimeout(function(){
iframe_el = document.getElementById("iframe1").contentDocument.createElement("div");
iframe_el.innerHTML = 'inside iframe';
document.getElementById("iframe1").contentDocument.body.appendChild(iframe_el);
},50);
no_iframe_el=document.createElement('div');
no_iframe_el.innerHTML = 'outside of iframe';
document.body.appendChild(no_iframe_el);
</script>
</body>
</html>
When i open in in a browser, the element created in a main document has red color, as expected, but the one in the iframe is black.
The problem is that I only have control on the script contained in the HEAD section of the document. In other words, i don't know how many iframes there will be later on in the HTML source, or how they will be names, or if they are added via user's Javascript.
My question is: how can i change the method globally, so all elements created in iframes also use this new style?
Thanks a lot!
Each frame has it's own separate Javascript context. If you want to change that frame's context, you have to do it specifically for that frame.
In your specific example, each frame has its own document object so it should be no surprise that each document has its own .createElement property.
You cannot generically change things in a way that will affect all frames. And, in fact if it's a cross-origin frame, you can't change it at all.
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.
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.
I have a page, with some code in js and jQuery and it works very well. But unfortunately, all my site is very very old, and uses frames. So when I loaded my page inside a frame, $(document).ready() doesn't fire up.
My frameset looks like:
<frameset rows="79,*" frameBorder="1" frameSpacing="1" bordercolor="#5996BF" noresize>
<frame name="header" src="Operations.aspx?main='Info.aspx'" marginwidth="0" marginheight="0" scrolling="no" noresize frameborder="0">
<frame name="main" src="Info.aspx" marginwidth="0" marginheight="0" scrolling="auto" noresize frameborder="0">
</frameset>
My page is loaded into the main frame. What should I do?
I have tried the method mentioned in another comment:
$("#frameName").ready(function() {
// Write you frame on load javascript code here
} );
and it did not work for me.
this did:
$("#frameName").load( function() {
//code goes here
} );
Even though the event does not fire as quickly - it waits until images and css have loaded also.
I know this is an old topic. But to help some of you who reach this page, here is my solution:
$($("#frameName")[0].contentWindow.document).ready(function() {
// Write you frame onready code here
});
I assume this is a similar problem I was having with DOMContentLoaded in an iframe.
I wrote a blog post about it.
If you want to fire the onload event for your frames, then follow these steps:
Assign an id and name to each <frame> tag. Make sure both id and name attributes value is same.
Use the following code to fire the onload event of the frame:
$("frameName").ready(function() {
// Write your frame onload code here
}
The following also worked for me:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>
$(window.parent.frames[0].document).ready(function() {
// Do stuff
});
</script>
The [0] indicates that it is the first frame in the document, [1] would be the second frame, and so on. This is particularly nice if you do not have control over the mark-up, and it is still utilizing document ready.
Have you tried to put the jQuery code inside the Info.aspx page?
Not sure what you're trying to do, but I have an even older classic asp app that operates out of frames, and I just recently added jQuery functionality and it is working great. The $(document).ready() works fine within a frame, but if you wish to reference the DOM in another frame, you'll have to use the Frame's onload event to let you know when the frame's DOM is loaded. Admittedly, I used iFrames, but the concept should be the same.
I have worked a long time with this post... here is my solution.
test.html
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
document.write('<frameset><frame name="frame_content" id="frame_content"></frame></frameset>');
$('#frame_content').attr('src', 'test2.html');
$('#frame_content').load(function()
{
if('${"#header"}' != '') {
$("#header", frame_content.document).remove();
}
});
if($('#frame_content').complete) $('#frame_content').trigger("load");
</script>
</head>
</html>
test2.html
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="header">You will never see me, cause I have been removed!</div>
</body>
</html>
I don't know if it is the best solution, but when I remove $(document).ready() and keep its body, everything works perfectly.
No need to modify the markup. Just fix the selector. It should be:
$("frame[name='main']").ready(function(){..});
not
$("#frameName").ready(function(){..});
Note: it seems the jQuery ready event fires multiple times. Make sure that is OK with your logic.
This answer may be late, but this reply may help someone like me...
This can be done via native Javascript code -
ifrm2 = var ifrm2 = document.getElementById('frm2');
if (ifrm2.contentDocument.readyState == 'complete') {
//here goes the code after frame fully loaded
}
//id = frm2 is the id of iframe in my page
There is no reason for $(document).ready() not to be called.
Be sure your page contains an include to jquery.js. Try to do a simple test with an empty HTML page and just an alert to see if there is another problem.
If you are trying to use this inside the HTML page that contains the frame's definition, keep in mind that there is no document there, you will have to use the