DNR
DNR

Reputation: 3736

javascript error: Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object

I am getting this error when I call a javascript function to display a modal window:

Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object

The code block is:

else if (action=="officeview") {
    document.getElementById("OfficeContent").src="ChangeView.aspx";
    ShowFeatureModal('AppView','OfficeContent')

The object is this situation, does exist.

Error is caused at: document.getElementById line. What else could be causing the error?

Update:
Index.aspx is calling the javascript function which is located in sysUtilities.js file. The source file is yet a seperate page (ChangeView.aspx)

Upvotes: 3

Views: 8186

Answers (4)

FishBasketGordo
FishBasketGordo

Reputation: 23142

If document.getElementById doesn't find the element, it will return null. If you then try to get the src property from null, you'll get this error.

You'll either need to ensure the there's an element with its ID equal to OfficeContent or do something like the following:

else if (action=="officeview") {
    var officeContent = document.getElementById("OfficeContent")
    if (officeContent) {
        officeContent.src="ChangeView.aspx";
        ShowFeatureModal('AppView','OfficeContent')
    }
}

EDIT: If you're using ASP.NET, which it appears that you are, remember that your IDs might be getting name-mangled if they are inside a container control. In that case, you have to make sure to use the ClientID, not the plain old ID. Something like this:

document.getElementById("<%= OfficeContent.ClientID %>")

Upvotes: 3

Peter Bromberg
Peter Bromberg

Reputation: 1496

All this stuff is peripheral to the main issue, which is:

You must use the actual clientID of "OfficeContent", which may be quite different in the HTML DOM of the page as it is rendered. One easy way to avoid this would look something like this:

var officeContent = document.getElementById("<%=OfficeContent.ClientID %>")

Upvotes: 0

wukong
wukong

Reputation: 2597

you need test whether an element exists first before setting element's src attribute

var el = document.getElementById("OfficeContent");
el && (el.src="ChangeView.aspx");

Upvotes: 0

KooiInc
KooiInc

Reputation: 122906

Don't know if it will help in this case, but this is a trick to prevent the error:

(document.getElementById("OfficeContent")||{}).src="ChangeView.aspx";

If the element doesn't exist, an empty object gets the src-property, no error is thrown, no harm is done.

It may be wise though to look for the cause of document.getElementById("OfficeContent") returning null.

Upvotes: 1

Related Questions