最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

overloading - JavaScript getElementById function overload - Stack Overflow

programmeradmin4浏览0评论

I have a problem with old website. All JavaScript code on it use getElemenById function. But tags of site markup doen't have id property, instead they have only name property. Although it still works for IE, browser returns elements even by name property. For all other browsers it's a mistake in JS. I wonder if there any way to overload this function in other browser to make web site patible to other browsers?

I have a problem with old website. All JavaScript code on it use getElemenById function. But tags of site markup doen't have id property, instead they have only name property. Although it still works for IE, browser returns elements even by name property. For all other browsers it's a mistake in JS. I wonder if there any way to overload this function in other browser to make web site patible to other browsers?

Share Improve this question asked Jul 28, 2011 at 7:32 Johnny_DJohnny_D 4,6524 gold badges35 silver badges65 bronze badges 1
  • 3 It would probably be better to fix the code so it works properly rather than try and hack the method to work differently on other browsers. You can use the getElementsByName method to find elements by name, although this returns an array as name is not expected to be unique like ID. – Richard Dalton Commented Jul 28, 2011 at 7:40
Add a ment  | 

3 Answers 3

Reset to default 11

There's no way to "overload" a function in JavaScript in the sense that you would do so in a strongly-typed language like Java or C. In fact, every function in JavaScript is already overloaded in this sense in that you can call any function with any number and type of arguments.

What you can do, however, is insert your own proxy in front of the existing version, and implement the proxy with whatever behavior you prefer. For instance:

document._oldGetElementById = document.getElementById;
document.getElementById = function(elemIdOrName) {
    var result = document._oldGetElementById(elemIdOrName);
    if (! result) {
        var elems = document.getElementsByName(elemIdOrName); 
        if (elems && elems.length > 0) {
            result = elems[0];
        }
    }

    return result;
};

I wouldn't count on overriding getElementById working properly. Sounds easy enough to do a search and replace that does something like this:

// Replace
document.getElementById("foo");
// With
myGetElementById("foo", document);

// Replace
myElement.getElementById("foo");
// With
myGetElementById("foo", myElement);

Then you can myGetElementById as you want, without worrying about what might happen in old IEs and what not if you override getElementById.

Try getElementsByName. This is used to get a collection of elements with respect to their name

发布评论

评论列表(0)

  1. 暂无评论