本文翻译自:document.getElementById vs jQuery $()

Is this: 这是:

var contents = document.getElementById('contents');

The same as this: 与此相同:

var contents = $('#contents');

Given that jQuery is loaded? 鉴于jQuery已加载?


#1楼

参考:https://stackoom.com/question/H4ms/document-getElementById-vs-jQuery


#2楼

In case someone else hits this... Here's another difference: 如果其他人遇到这个...这是另一个区别:

If the id contains characters that are not supported by the HTML standard (see SO question here ) then jQuery may not find it even if getElementById does. 如果id包含HTML标准不支持的字符(请参阅此处的 SO问题),那么即使getElementById,jQuery也可能找不到它。

This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome: 使用Chrome时,我发现我的ID包含“/”字符(例如:id =“a / b / c”):

var contents = document.getElementById('a/b/c');

was able to find my element but: 能够找到我的元素但是:

var contents = $('#a/b/c');

did not. 没有。

Btw, the simple fix was to move that id to the name field. 顺便说一句,简单的解决方法是将id移动到name字段。 JQuery had no trouble finding the element using: JQuery使用以下方法找到元素没有问题:

var contents = $('.myclass[name='a/b/c']);

#3楼

One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc. 另一个区别是: getElementById返回第一个匹配,而$('#...')返回匹配集合 - 是的,可以在HTML文档中重复相同的ID。

Further, getElementId is called from the document, while $('#...') can be called from a selector. 此外,从文档中调用getElementId ,而可以从选择器调用$('#...') So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form. 因此,在下面的代码中, document.getElementById('content')将返回整个正文,但$('form #content')[0]将返回表单内部。

<body id="content"><h1>Header!</h1><form><div id="content"> My Form </div></form>
</body>

It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. 使用重复的ID可能看起来很奇怪,但如果您使用的是Wordpress,模板或插件可能会使用与您在内容中使用的ID相同的ID。 The selectivity of jQuery could help you out there. jQuery的选择性可以帮助你。


#4楼

var contents = document.getElementById('contents');

var contents = $('#contents');

The code snippets are not the same. 代码片段不一样。 first one returns a Element object ( source ). 第一个返回一个Element对象( 源 )。 The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. 第二个,jQuery等价物将返回一个包含零个或一个DOM元素集合的jQuery对象。 ( jQuery documentation ). ( jQuery文档 )。 Internally jQuery uses document.getElementById() for efficiency. 在内部,jQuery使用document.getElementById()来提高效率。

In both the cases if more than one element found only the first element will be returned. 在这两种情况下,如果找到多个元素,则只返回第一个元素。


When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes ( https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards) 当检查github项目的jQuery时,我发现以下行代码片段似乎使用了document.getElementById代码( https://github.com/jquery/jquery/blob/master/src/core/init.js第68行)

// HANDLE: $(#id)
} else {elem = document.getElementById( match[2] );

#5楼

A note on the difference in speed. 关于速度差异的说明。 Attach the following snipet to an onclick call: 将以下snipet附加到onclick调用:

function myfunc()
{var timer = new Date();for(var i = 0; i < 10000; i++){//document.getElementById('myID');$('#myID')[0];}console.log('timer: ' + (new Date() - timer));
}

Alternate commenting one out and then comment the other out. 替代评论一个,然后评论另一个。 In my tests, 在我的测试中,

document.getElementbyId averaged about 35ms (fluctuating from 25ms up to 52ms on about 15 runs ) document.getElementbyId平均大约35ms (在大约15 runs25ms52ms波动)

On the other hand, the 另一方面,

jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs ). jQuery平均大约200ms (大约15 runs181ms222ms )。

From this simple test you can see that the jQuery took about 6 times as long. 从这个简单的测试中你可以看到jQuery花了大约6倍的时间。

Of course, that is over 10000 iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate and .fadeTo . 当然,这是超过10000次迭代,因此在更简单的情况下,我可能会使用jQuery易用性和所有其他很酷的东西,如.animate.fadeTo But yes, technically getElementById is quite a bit faster . 但是,从技术上讲, getElementById快得多 。


#6楼

I developed a noSQL database for storing DOM trees in Web Browsers where references to all DOM elements on page are stored in a short index. 我开发了一个用于在Web浏览器中存储DOM树的noSQL数据库,其中对页面上所有DOM元素的引用存储在一个短索引中。 Thus function "getElementById()" is not needed to get/modify an element. 因此,获取/修改元素不需要函数“getElementById()”。 When elements in DOM tree are instantiated on page the database assigns surrogate primary keys to each element. 当DOM树中的元素在页面上实例化时,数据库会为每个元素分配代理主键。 It is a free tool http://js2dx.com 它是一个免费的工具http://js2dx.com

document.getElementById vs jQuery $()相关推荐

  1. document.getElementById()

    句法: var element = document .getElementById(id); 参量: id:要定位的元素的id.id是区分大小写的字符串,且在文档中是唯一的.只有一个元素可以具有任何 ...

  2. $(document).click()在iPhone上无法正常工作jQuery

    如何解决$(document).click()在iPhone上无法正常工作jQuery? 添加以下代码即可. 问题是iPhone不会引发点击事件.他们引发"触摸"事件.非常感谢苹果 ...

  3. document.getElementById与getElementsByName的区别(注意后者多个S)

    1:id   就像身分证号,是唯一的,   name   就像姓名一样可以同名 2:一个元素定义了   id   ,引用该元素时直接用   id   属性,而   name   通常用在   form ...

  4. document.getelementbyid css,使用document.getElementById()从css获取值。style.height javascript...

    我试图通过 var high = document.getElementById("hintdiv").style.height; alert(high); 摆脱一个div框高度值 ...

  5. JavaScript核心之Document对象详解(document属性,方法)

    目录 1 Document节点概述 2 document节点的属性 2.1 doctype,documentElement,defaultView,body,head,activeElement 2. ...

  6. 已解决(from docx import Document导包报错)ModuleNotFoundError: No module named ‘exceptions‘

    已解决(from docx import Document导包报错)ModuleNotFoundError: No module named 'exceptions' 文章目录 报错代码 报错翻译 报 ...

  7. php document.write,在JS中有关document.write()的用法(详细教程)

    这篇文章主要介绍了JS 中document.write()的用法和清空的原因浅析,需要的朋友可以参考下 可能很多朋友都遇到过这样的情况,那就是使用document.write()函数向网页中写内容的时 ...

  8. 转:【CSS/JS学习】如何实现单行/多行文本溢出的省略(...)--老司机绕过坑道的正确姿势...

    本文来源:http://www.cnblogs.com/penghuwan/p/6682303.html 引言: 写前端UI的朋友们也许都遇到过这样的问题:我们需要实现这样一个需求,在一个父级元素中隐 ...

  9. document.getElementById()和document.forms[0].submit()

    下午,做一个jsp文件,涉及到document.getElementById()以及document.forms[0].submit()的使用,折腾了好长时间. 1.document.getEleme ...

最新文章

  1. quartz mysql 初始化_quartz2.3.0(十五)执行、暂停、继续执行、清除,花式操作数据库中持久化的job任务...
  2. 为什么要尽量设定一个主键?
  3. 虚机如果要访问SAN中的多个LUN,如何实现高可用
  4. VTK:PolyData之LinearExtrusion
  5. rabbitmq消息可靠投递(理论)
  6. 硬件:电脑DNS出现错误对应的解决方案
  7. ai字体行间距怎么调整_字体基础知识(一)
  8. ios学习之UITabBar(标签栏)
  9. php输出mysql的数据结构_php课程 13-43 mysql的数据结构是什么
  10. sql server 跟踪_SQL Server跟踪标志指南; 从-1到840
  11. Java面试必看的18个开源项目
  12. 由于未安装.net framework 4.0的miscrosoft office支持,无法加载以下解决方案 ***.vsto
  13. 程序员今年最值得关注的 23 种新移动技术
  14. vs2017 开关“/NOENTRY”只与 DLL 兼容;链接时不使用“/NOENTRY”
  15. 计算机硬盘copy,diskgenius硬盘拷贝的方法
  16. 计算机科学丛书之第9章和第10章代码
  17. redis 指定端口 启动
  18. 微信小程序客服功能,并在聊天页面获取用户头像昵称
  19. 软件流水和循环展开的区别
  20. PHP微信公众平台自定义菜单

热门文章

  1. 访客模式(Guest Mode)
  2. Ubuntu中Vim 中文乱码解决方法
  3. Android之四大组件(Activity)
  4. Shell-bash
  5. 百度地图搜索返回地址中经纬度为null
  6. 【RxSwift】flatMapLatest、 Error事件中断序列
  7. (0033) iOS 开发之Block 的基础用法及注意事项2
  8. swift_025(Swift 的自动引用计数(ARC)
  9. linux 互斥锁销毁_c-销毁锁定的互斥锁时pthread_mutex_destroy的正...
  10. linux日常运维手册_Linux日常运维上传下载工具lrzsz