jquery $() 和document.getElementById() 区别

jQuery的$()和document.getElementById()的区别
2011-05-18 17:57

原文链接: http://codeclimber.net.nz/archive/2008/04/11/beware-the-.-in-jquery-elementid-document.getelementbyidelementid.aspx

 $("element").get(0)=document.getElementById("element");

Lately I've been playing a bit with jQuery, one of the raising javascript frameworks and I found out something I was not expecting to find.

But let's step back a bit: in jQuery the dollar sign function $ is a shortcut for themain function of the framework which is used to select html elements in the page. This$ method accepts a css-like selector as argument, so if you want to select a specific element by its id you have to use the hash:$("#myElementId") returns a reference to the DOM element boosted by jQuery. We can say it's a shortcut to the usual way of getting a DOM elementdocument.getElementById("myElementId").

With this idea in mind, thinking that jQuery added its goodness to the standard DOM Element via extension methods, and after reading on the docs thatwhen called with the id selector the jQuery method returned a DOM Element, I was expecting to get a reference to the real DOM element. So I passed it to an ASP.NET Javascript function and it complained that the DOM element didn't have a style property. Where was I wrong?

It took me a while to understand why I was wrong: the $ method gives a jQuery object that isalways an array of Elements, even if the docs say otherwise.

dollarsign-vs-getelementbyid.jpg

So to the get the real DOM element you have to use $("#myElementId")[0] or the more friendly$("#myElementId").get(0)

jquery-element-array-zero.jpg

So, just to wrap up, $("#elementId") != document.getElementById("elementId"). And comparing to the ASP.NET Ajax Library, it is also different from the$get("elementId") which is exactly the same as doing the getElementById the old way.

It took me a whole afternoon to understand this... I hope this post will save you 4 hours of your time as well.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值