document.getElementById in IE - javascript

When I use document.getElementById in Internet Explorer I get this error:
Mensaje: El objeto no acepta esta propiedad o método
Translation:
Object does not support this property or method
and the execution stops
Html:
<div id="contenedor">
...
</div>
JavaScript:
contenedor = document.getElementById("contenedor");
This works ok in Firefox and Chrome.

There is a misfeature in some(?) versions of IE where it defines global constants for every id value in the document. So when you write contenedor = document.getElementById("contenedor") — notice that it uses the div's name for the variable — it sees you're trying to set that global variable and complains that you can't. What you should do is declare a new variable instead of setting a global: var contenedor = document.getElementById("contenedor")

If it's simply document.getElementById('someid') that gives you this message, may be placing your script at the bottom of the HMTL (right before the closing </body> tag) will help.
if you want to be shure the element is loaded before you assign it to a variable, use
window.onload = function(){
contenedor = document.getElementById("contenedor");
};

It looks like your javascript is executing before DOM is ready. Many javascript libraries include a mechanism for adding an event when DOM is ready, otherwise, one can use the body onload event.
You can try to put your javascript at the bottom of your document, but this is no guarantee that the code won't be executed before the page has loaded sufficiently to allow the browser to build the DOM tree. You're much better off either using a framework with the ready or domready event (like mootools or jquery), OR using the body onload event as mentioned.
Example:
<html>
<head>
<script type="text/javascript">
var initPage = function() {
// do stuff
}
</script>
</head>
<body onload="initPage();">
<!-- page content -->
</body>
</html>

Related

getElementById unable to find the mistake in loop [duplicate]

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>

My code gives me an error message: GetElementById() is null or not an object

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.
}

Javascript: Best place to register event handlers

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
});

Javascript can't find element by id? [duplicate]

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.

Javascript onload in HTML

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); })

Categories

Resources