简体   繁体   中英

document.getElementById in IE

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM