JS: How to make document.getElementById cross-browser?

后端 未结 4 709
清歌不尽
清歌不尽 2020-12-18 04:28

document.getElementById doesn\'t seem to work across all browsers (I mean some old ones) and I am sure there are developers who are not aware of this.

相关标签:
4条回答
  • 2020-12-18 05:11
    function getDOM() {
        if (document.getElementById) {
            return document.getElementById; 
        }
    
        var window_document = window.document || {};
        var elements = window_document.all || window_document.layers;
        if(elements) {
            return function(x) { return elements[x]; }
        }
    
        // everything failed
        throw new InternalError('No means to "getElementById"');
    }
    

    ... then

    var getElementById;
    try {
        getElementById = getDOM();
    } catch(err) {
        alert(err);
    }
    // implicit 0K
    var oHTMLElement = getElementById('#main');
    
    0 讨论(0)
  • 2020-12-18 05:20
    getElemID(obj){
    
    if(document.getElementByID){
     return document.getElementByID(obj);
    }
    
     else if (document.all){
      return document.all[obj];
      }
    
      else if (document.layers){
         return  document.layers[obj];
         }
    
      else {
           alert("Could not find support");
           return false;
           }
    }
    
    0 讨论(0)
  • 2020-12-18 05:22

    If document.getElementById doesn't work then either:

    • You're doing it wrong (invalid HTML, trying to access names instead of IDs, etc)

    or

    • You're working with Netscape 4.x and Internet Explorer 4.x

    There are three ways to deal with browsers of this era.

    • Tell people to upgrade. They are unmaintained, security hole ridden nightmares for user and author alike.
    • Build on stuff that works and make sure your JS checks for the existence of getElementById and friends before trying to use them ( if (!document.getElementById) { return false; /* Insufficient DOM to bother with JS here */ } )
    • Learn about document.all and document.layers
    0 讨论(0)
  • 2020-12-18 05:32

    Are you sure its not this kind of problem? Have a look its interesting, I didn't know that before.

    However, to complement what is already suggested by David Dorward, you write a function like below.

    function getElement (id) {
    
      if (document.getElementById) {
        return document.getElementById(id);
      }
    
      else if (document.all) {
        return window.document.all[id];
      }
    
      else if (document.layers) {
        return window.document.layers[id];
      }
    } 
    
    0 讨论(0)
提交回复
热议问题