document.getelementbyid vs dom.byid

document.getelementbyid vs dom.byid

本文关键字:byid dom vs getelementbyid document      更新时间:2023-09-26

下面是一些代码

  var docDiv= document.getElementById("divId");
  var dojoDiv= dom.byId("divId");

javascript的文档有什么不同?Getelementbyid和dojo的dom.byid。又快了一个。如果你想使用dom,我们需要加载dojo.js。

这是Dojo dom的非IE版本。byId:

dom.byId = function(id, doc){
            // inline'd type check.
            // be sure to return null per documentation, to match IE branch.
            return ((typeof id == "string") ? (doc || win.doc).getElementById(id) : id) || null; // DOMNode
        };

你会注意到它使用了getElementById。

希望这能回答你的问题

我认为document.getElementById()dom.byId()快,因为dojo是内部使用的document .

document.getElementById()dom.byId()快。因为dom.byId()需要加载dojo核心文件

from dojo github code https://github.com/dojo/dojo/blob/master/dom.js#L51,它在内部使用document.getElementById

dom.byId = function(id, doc){
    // inline'd type check.
    // be sure to return null per documentation, to match IE branch.
    return ((typeof id == "string") ? (doc || win.doc).getElementById(id) : id) || null; // DOMNode
};
使用document.getElementById,我们可以避免调用这个dom.byId函数!但是性能差异非常小

我更喜欢dom.byId,因为它使用起来很短。否则我必须在每个地方都写冗长的document.getElementById !