Friday, November 27, 2009

Solution for IE: "is null or not an object"?

I have a problem with some Javascript that only occurs in IE (not in Firefox and Opera).

I use a script to build a table using the DOM. That works fine. Each table-cell gets an id and a javascript-script. Each of these scripts looks for the cell with that id and replaces its contents.

Code for building the table (it loops through an array, for each element:)

var cell=document.createElement("td");



var scr=document.createElement("script");





Code that tries to fill the cell:

var goal = document.getElementById(4);

var text = "test";

goal.innerHTML = text;

When I visit the page using IE, is says "goal is null or not an object".I have tried a lot to solve the problem and have been trying to look for a solution via search engines, forums, etc. I am getting a bit desperate.

Solution for IE: "is null or not an object"?microsoft support

IE is riddled with separate bugs on setAttribute so I certainly would not use it for cross-browser code. However in this case, it is not actually setAttribute that is causing the problem, but appendChild. The attribute is not actually being set on the real cell here in IE but on a copy, but works fine in Firefox.

This works in all browsers::




var tbl=document.createElement( "table");

var row = tbl.insertRow(0);

var cell;

for(i=0; i%26lt; 5; i++) {

cell = row.insertCell(i);

cell.setAttribute('id' , i);



document.body.appendChild( tbl);

var goal = document.getElementById(4);

var text = "test";

goal.innerHTML = text;


This works because we are now setting the attribute on the actual cell which we've inserted using the insertCell method which does work in both browsers.

appendChild doesn't do exactly the same thing in IE because it's a copy - you have to use cloneNode but for tables use the above method.

The reason why you get a null or not an object is because goal is null in IE because the id 4 has been set on the copy cell and not the real cell.

Hope this helps.

Solution for IE: "is null or not an object"?windows live mail internet explorer

if this works with other browsers,

if goal is null or not an object, then

var goal = document.getElementById(4) is a problem

getElementById(**this might be the problem**), you might have to change 4, to the id names. IE might not recognise 4 as a id or tag or reference to ids.

No comments:

Post a Comment

shared web hosting