Memochipan
Memochipan

Reputation: 3465

Why this Javascript code fails in IE7-8?

I have this code:

window.addEvent('domready', function() {

  var li_list = document.getElementById("topmenu").getElementsByTagName("li");

  for (var i=0; i<li_list.length; i++) {

      li_list[i].onmouseover=function() {
          this.className+=" hover";
      }

      li_list[i].onmouseout=function() {
          this.className=this.className.replace(new RegExp(" hover\\b"), "");
      }
  }
})

In IE7-8 it fails: document.getElementById(...) is null or not an object.

In Firefox it works well.

That affect the main menu function of the site: http://paraguasparados.com

Thanks.

Upvotes: 0

Views: 468

Answers (3)

Darthg8r
Darthg8r

Reputation: 12675

Use jquery, they have done the leg work getting it to work cross browser.

$(document).ready(function() {
// do some stuff here
});

Upvotes: 1

Larry K
Larry K

Reputation: 49104

On IE, domready can fire before the dom is actually ready. Post.

So then document object is not yet available when your code is executed. (Hence the IE error message "document.getElementById(...) is null or not an object.")

Solution: use a toolkit (jQuery, yui, etc) to provide the equivalent of domready that works on IE and other browsers.

Upvotes: 4

Will
Will

Reputation: 20235

Try this instead. This should only work in IE though.

document.attachEvent( "onreadystatechange", function() {
    if ( document.readyState === "complete" ) {
        // dom ready
    }
});

Upvotes: 3

Related Questions