简体   繁体   English

document.getElementById 与 jQuery $()

[英]document.getElementById vs jQuery $()

Is this:这是:

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

The same as this:与此相同:

var contents = $('#contents');

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

Not exactly!!不完全是!!

document.getElementById('contents'); //returns a HTML DOM Object

var contents = $('#contents');  //returns a jQuery Object

In jQuery, to get the same result as document.getElementById , you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).在 jQuery 中,要获得与document.getElementById相同的结果,您可以访问 jQuery 对象并获取该对象中的第一个元素(请记住,JavaScript 对象的行为类似于关联数组)。

var contents = $('#contents')[0]; //returns a HTML DOM Object

No.没有。

Calling document.getElementById('id') will return a raw DOM object.调用document.getElementById('id')将返回一个原始 DOM 对象。

Calling $('#id') will return a jQuery object that wraps the DOM object and provides jQuery methods.调用$('#id')将返回一个包含 DOM 对象并提供 jQuery 方法的 jQuery 对象。

Thus, you can only call jQuery methods like css() or animate() on the $() call.因此,您只能在$()调用上调用 jQuery 方法,如css()animate()

You can also write $(document.getElementById('id')) , which will return a jQuery object and is equivalent to $('#id') .你也可以写$(document.getElementById('id')) ,它会返回一个 jQuery 对象,相当于$('#id')

You can get the underlying DOM object from a jQuery object by writing $('#id')[0] .您可以通过编写$('#id')[0]从 jQuery 对象获取底层 DOM 对象。

A note on the difference in speed.关于速度差异的说明。 Attach the following snipet to an onclick call:将以下代码附加到 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 runs25ms波动到52ms

On the other hand, the另一方面,该

jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs ). jQuery的平均200ms左右(范围从181ms222ms上约15 runs )。

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速度要快一些

Close, but not the same.接近,但不一样。 They're getting the same element, but the jQuery version is wrapped in a jQuery object.他们得到相同的元素,但 jQuery 版本被包装在一个 jQuery 对象中。

The equivalent would be this等价物是这个

var contents = $('#contents').get(0);

or this或者这个

var contents = $('#contents')[0];

These will pull the element out of the jQuery object.这些将从 jQuery 对象中拉出元素。

No. The first returns a DOM element, or null, whereas the second always returns a jQuery object.不。第一个返回一个 DOM 元素,或者 null,而第二个总是返回一个 jQuery 对象。 The jQuery object will be empty if no element with the id of contents was matched.如果没有与contents id 匹配的元素,则 jQuery 对象将为空。

The DOM element returned by document.getElementById('contents') allows you to do things such as change the .innerHTML (or .value ) etc, however you'll need to use jQuery methods on the jQuery Object. document.getElementById('contents')返回的 DOM 元素允许您执行诸如更改.innerHTML (或.value )等操作,但是您需要在 jQuery 对象上使用jQuery 方法

var contents = $('#contents').get(0);

Is more equivilent, however if no element with the id of contents is matched, document.getElementById('contents') will return null, but $('#contents').get(0) will return undefined.更等价的是,如果没有与contents id 匹配的元素, document.getElementById('contents')将返回 null,但$('#contents').get(0)将返回 undefined。

One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned.使用 jQuery 对象的一个​​好处是,如果没有返回任何元素,您将不会收到任何错误,因为始终返回一个对象。 However you will get errors if you try to perform operations on the null returned by document.getElementById但是,如果您尝试对document.getElementById返回的null执行操作,则会出现错误

No, actually the same result would be:不,实际上相同的结果是:

$('#contents')[0] 

jQuery does not know how many results would be returned from the query. jQuery 不知道查询会返回多少结果。 What you get back is a special jQuery object which is a collection of all the controls that matched the query.您返回的是一个特殊的 jQuery 对象,它是与查询匹配的所有控件的集合。

Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection jQuery 如此方便的部分原因在于,在这个对象上调用的大多数方法看起来像是用于一个控件,实际上是在一个循环中调用集合中的所有成员

When you use the [0] syntax you take the first element from the inner collection.当您使用 [0] 语法时,您从内部集合中获取第一个元素。 At this point you get a DOM object此时你得到一个 DOM 对象

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:这发生在我身上,ID 包含“/”字符(例如:id="a/b/c"),使用 Chrome:

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']);

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 的选择性可以帮助你。

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

var contents = $('#contents');

The code snippets are not the same.代码片段不一样。 first one returns a Element object ( source ).第一个返回一个Element对象( source )。 The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element.第二个,jQuery 等效项将返回一个 jQuery 对象,其中包含零个或一个 DOM 元素的集合。 ( 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)在检查 jQuery 的 github 项目时,我发现以下几行代码片段似乎在使用 document.getElementById 代码( https://github.com/jquery/jquery/blob/master/src/core/init.js第 68 行)

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

Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript.正如大多数人所说,主要区别在于它使用 jQuery 调用包装在 jQuery 对象中,而不是使用直接 JavaScript 的原始 DOM 对象。 The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. jQuery 对象当然可以使用它来执行其他 jQuery 函数,但是,如果您只需要执行简单的 DOM 操作,例如基本样式或基本事件处理,那么直接的 JavaScript 方法总是比 jQuery 快一点,因为您不需要不必加载基于 JavaScript 的外部代码库。 It saves an extra step.它节省了一个额外的步骤。

jQuery is built over JavaScript. jQuery 是基于 JavaScript 构建的。 This means that it's just javascript anyway.这意味着无论如何它都只是 javascript。

document.getElementById() document.getElementById()

The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page. document.getElementById() 方法返回具有指定值的 ID 属性的元素,如果不存在具有指定 ID 的元素,则返回 null。ID 在页面内应该是唯一的。

Jquery $() jQuery $()

Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document.使用 id 选择器作为参数调用 jQuery() 或 $() 将返回一个 jQuery 对象,该对象包含零个或一个 DOM 元素的集合。每个 id 值在文档中只能使用一次。 If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.如果多个元素被分配了相同的 ID,则使用该 ID 的查询将只选择 DOM 中第一个匹配的元素。

All the answers above are correct.以上所有答案都是正确的。 In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :如果您想看到它的实际效果,请不要忘记您在浏览器中有控制台,您可以在其中清楚地看到实际结果:

I have an HTML :我有一个 HTML :

<div id="contents"></div>

Go to console (cntrl+shift+c) and use these commands to see your result clearly转到控制台(cntrl+shift+c)并使用这些命令清楚地查看您的结果

document.getElementById('contents')
>>> div#contents

$('#contents')
>>> [div#contents,
 context: document,
 selector: "#contents",
 jquery: "1.10.1",
 constructor: function,
 init: function …]

As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object).正如我们所见,在第一种情况下,我们得到了标签本身(严格来说,就是一个 HTMLDivElement 对象)。 In the latter we actually don't have a plain object, but an array of objects.在后者中,我们实际上没有一个普通对象,而是一个对象数组。 And as mentioned by other answers above, you can use the following command:正如上面其他答案所提到的,您可以使用以下命令:

$('#contents')[0]
>>> div#contents

Is this:这是:

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

The same as this:与此相同:

var contents = $('#contents');

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

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it截至 2019 年,今天所有的答案都是旧的,您可以直接在 javascript 中访问 id 键控的字段,只需尝试一下

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo!在线演示! - https://codepen.io/frank-dspeed/pen/mdywbre - https://codepen.io/frank-dspeed/pen/mdywbre

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM