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

后端 未结 4 734
清歌不尽
清歌不尽 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');
    

提交回复
热议问题