开发者

Is there a reason to not use a shorthand for document.getElementById?

I wrote something that uses document.getElementBy开发者_JAVA技巧Id a lot so I was wondering if instead I should just make a function like:

function gid (id) {
return document.getElementById(id);
}

and then just call it like:

alert(gid("test").innerText);


No, there's no reason not to. Typically most people use jQuery for stuff like this though.


It's a good idea - it'll aid minification (if you chose to minify) and will save annoying spelling mistakes when you accidently type document.getElementsById. You can also shorten document.getElementsByTagName if you use it a lot.


I don't think it's a bad idea. For one calls to gid() are going to be shorter than document.getElementById(). Plus you now have the ability to modify what is in your gid function so that you can use something other than document.getElementById.


Using document.getElementById will only make it faster when you have a huge javascript and not using any standard library like JQuery.


I'm not saying that you should not provide a replacement function, but there are some downsides so you should make sure the balance is in favor of changing. A couple reasons not to shorten it:

  1. It's now non-standard looking code that other people who know DOM/Javascript won't recognize and will have to learn before they can make sense of.
  2. It's one extra function call so presumably, your new extra function isn't quite as fast.
  3. You are losing the functionality of addressing different documents or document fragments (though not used very frequently).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜