Javascript document.getElementById 与 jQuery $()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4069982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:20:57  来源:igfitidea点击:

document.getElementById vs jQuery $()

javascriptjqueryjquery-selectors

提问by Phillip Senn

Is this:

这是:

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

The same as this:

与此相同:

var contents = $('#contents');

Given that jQuery is loaded?

鉴于 jQuery 已加载?

回答by John Hartsock

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

回答by SLaks

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.

因此,您只能像调用css()animate()$()调用时调用 jQuery 方法。

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].

您可以通过编写从 jQuery 对象获取底层 DOM 对象$('#id')[0]

回答by RightSaidFred

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 对象中拉出元素。

回答by nurdyguy

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 25msup to 52mson about 15 runs)

的document.getElementById平均大约为35ms(波动从25ms最高52ms的约15 runs

On the other hand, the

另一方面,该

jQuery averaged about 200ms(ranging from 181msto 222mson about 15 runs).

From this simple test you can see that the jQuery took about 6 timesas long.

jQuery 平均大约200 毫秒(从181ms222ms大约15 runs)。

从这个简单的测试中,您可以看到 jQuery 花费了大约6 倍的时间。

Of course, that is over 10000iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animateand .fadeTo. But yes, technically getElementByIdis quite a bit faster.

当然,这已经结束了10000迭代,所以在更简单的情况下,我可能会使用 jQuery 以方便使用以及所有其他很酷的东西,比如.animate.fadeTo。但是,是的,在技术上getElementById是相当多

回答by Matt

No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contentswas matched.

不。第一个返回一个 DOM 元素,或者 null,而第二个总是返回一个 jQuery 对象。如果没有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 methodson the jQuery Object.

返回的 DOM 元素document.getElementById('contents')允许您执行诸如更改.innerHTML(或.value) 等操作,但是您需要在 jQuery 对象上使用jQuery 方法

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

Is more equivilent, however if no element with the id of contentsis 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. However you will get errors if you try to perform operations on the nullreturned by document.getElementById

使用 jQuery 对象的一个​​好处是,如果没有返回任何元素,您将不会收到任何错误,因为始终返回一个对象。但是,如果您尝试对null返回的对象执行操作,则会出现错误document.getElementById

回答by Andrey

No, actually the same result would be:

不,实际上相同的结果是:

$('#contents')[0] 

jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.

jQuery 不知道查询会返回多少结果。您返回的是一个特殊的 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. At this point you get a DOM object

当您使用 [0] 语法时,您从内部集合中获取第一个元素。此时你得到一个 DOM 对象

回答by user1435666

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. JQuery had no trouble finding the element using:

顺便说一句,简单的解决方法是将该 id 移动到 name 字段。JQuery 使用以下方法轻松找到元素:

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

回答by Kobby

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. 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. It saves an extra step.

正如大多数人所说,主要区别在于它使用 jQuery 调用包装在 jQuery 对象中,而不是使用直接 JavaScript 的原始 DOM 对象。jQuery 对象当然可以使用它来执行其他 jQuery 函数,但是,如果您只需要执行简单的 DOM 操作,例如基本样式或基本事件处理,那么直接的 JavaScript 方法总是比 jQuery 快一点,因为您不需要不必加载基于 JavaScript 的外部代码库。它节省了一个额外的步骤。

回答by Nipuna

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

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

var contents = $('#contents');

var contents = $('#contents');

The code snippets are not the same. first one returns a Elementobject (source). The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById()for efficiency.

代码片段不一样。第一个返回一个Element对象()。第二个,jQuery 等效项将返回一个 jQuery 对象,其中包含零个或一个 DOM 元素的集合。(jQuery 文档)。jQuerydocument.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.jsline 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] );

回答by steve banks

One other difference: getElementByIdreturns the firstmatch, while $('#...')returns a collection of matches - yes, the same ID can be repeated in an HTML doc.

另一个区别:getElementById返回第一个匹配项,而$('#...')返回匹配项集合 - 是的,可以在 HTML 文档中重复相同的 ID。

Further, getElementIdis called from the document, while $('#...')can be called from a selector. So, in the code below, document.getElementById('content')will return the entire body but $('form #content')[0]will return inside of the form.

此外,getElementId从文档中调用,而$('#...')可以从选择器中调用。因此,在下面的代码中,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. The selectivity of jQuery could help you out there.

使用重复的 ID 似乎很奇怪,但如果您使用的是 Wordpress 之类的东西,模板或插件可能会使用与您在内容中使用的 ID 相同的 ID。jQuery 的选择性可以帮助你。