document.getElementById 与 jQuery $()

发布于 2024-09-30 18:24:02 字数 182 浏览 3 评论 0 原文

这是:

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

与此相同:

var contents = $('#contents');

鉴于 jQuery 已加载?

Is this:

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

The same as this:

var contents = $('#contents');

Given that jQuery is loaded?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

ら栖息 2024-10-07 18:24:02

不完全是!!

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

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

在 jQuery 中,要获得与 document.getElementById 相同的结果,您可以访问 jQuery 对象并获取该对象中的第一个元素(请记住 JavaScript 对象的行为类似于关联数组)。

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

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

var contents = $('#contents')[0]; //returns a HTML DOM Object
茶色山野 2024-10-07 18:24:02

不会。

调用 document.getElementById('id') 将返回原始 DOM 对象。

调用 $('#id') 将返回一个包装 DOM 对象并提供 jQuery 方法的 jQuery 对象。

因此,您只能在 $() 调用中调用 css()animate() 等 jQuery 方法。

您还可以编写 $(document.getElementById('id')),它将返回一个 jQuery 对象,相当于 $('#id')

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

No.

Calling document.getElementById('id') will return a raw DOM object.

Calling $('#id') will return a jQuery object that wraps the DOM object and provides jQuery methods.

Thus, you can only call jQuery methods like css() or animate() on the $() call.

You can also write $(document.getElementById('id')), which will return a jQuery object and is equivalent to $('#id').

You can get the underlying DOM object from a jQuery object by writing $('#id')[0].

海未深 2024-10-07 18:24:02

关于速度差异的注释。将以下片段附加到 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));
}

交替注释一个,然后注释另一个。在我的测试中,

document.getElementbyId 平均约为35ms(在大约15次运行中从25ms波动到52ms)< /p>

document.getElementbyId 平均约为 35ms(在 , 这

jQuery 平均约为200ms(运行约15 次,范围从181ms222ms)。

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

当然,这已经超过了 10000 次迭代,因此在更简单的情况下,我可能会使用 jQuery 以便于使用以及所有其他很酷的东西,例如 .animate 和 。 >.fadeTo。但是,是的,从技术上来说,getElementById更快

A note on the difference in speed. Attach the following snipet to an onclick call:

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)

On the other hand, the

jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs).

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

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. But yes, technically getElementById is quite a bit faster.

疯了 2024-10-07 18:24:02

接近,但不一样。他们获得相同的元素,但 jQuery 版本包装在 jQuery 对象中。

等价的是 this

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

或 this

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

这些将从 jQuery 对象中提取元素。

Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.

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.

人│生佛魔见 2024-10-07 18:24:02

否。第一个返回 DOM 元素或 null,而第二个始终返回 jQuery 对象。如果没有匹配到 id 为 contents 的元素,则 jQuery 对象将为空。

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

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

更等效,但是如果没有匹配 id 为 contents 的元素,则 document.getElementById('contents') 将返回 null,但 $('# content').get(0) 将返回未定义。

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

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 contents was matched.

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.

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.

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 null returned by document.getElementById

难如初 2024-10-07 18:24:02

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

$('#contents')[0] 

jQuery 不知道查询会返回多少结果。您返回的是一个特殊的 jQuery 对象,它是与查询匹配的所有控件的集合。

jQuery 如此方便的部分原因是,在此对象上调用的大多数方法看起来像是针对一个控件,实际上是在一个循环中对集合中的所有成员进行调用

当您使用 [0] 语法时,您将采用第一个来自内部集合的元素。此时你就得到了一个DOM对象

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.

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

When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object

芯好空 2024-10-07 18:24:02

万一其他人碰到了这个...这是另一个区别:

如果 id 包含 HTML 标准不支持的字符(请参阅SO问题 此处),那么即使 getElementById 找到,jQuery 也可能找不到它。

这发生在我身上,id 包含“/”字符(例如:id="a/b/c"),使用 Chrome:

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

能够找到我的元素,但是:

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

没有。

顺便说一句,简单的修复方法是将 id 移至名称字段。 JQuery 使用以下命令可以轻松找到元素:

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

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.

This happened to me with an id containing "/" characters (ex: id="a/b/c"), using 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:

var contents = $('.myclass[name='a/b/c']);
梦年海沫深 2024-10-07 18:24:02

varcontents = document.getElementById('contents');

varcontents = $('#contents');

代码片段不一样。第一个返回一个 Element 对象()。
第二个,jQuery 等效项将返回一个 jQuery 对象,其中包含零个或一个 DOM 元素的集合。 (jQuery 文档)。 jQuery 在内部使用 document.getElementById() 来提高效率。

在这两种情况下,如果找到多个元素,则仅返回第一个元素。


在检查 jQuery 的 github 项目时,我发现以下行片段似乎使用 document.getElementById 代码(https://github.com/jquery/jquery/blob/master/src/core/init.js 第 68 行开始)

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

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

var contents = $('#contents');

The code snippets are not the same. first one returns a Element object (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.

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)

// HANDLE: $(#id)
} else {
    elem = document.getElementById( match[2] );
吃颗糖壮壮胆 2024-10-07 18:24:02

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

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.

那一片橙海, 2024-10-07 18:24:02

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

此外,getElementId 是从文档中调用的,而 $('#...') 可以从选择器中调用。因此,在下面的代码中, document.getElementById('content') 将返回整个正文,但 $('form #content')[0] 将返回内部形式。

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

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

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.

Further, getElementId is 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.

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

紙鸢 2024-10-07 18:24:02

jQuery 是基于 JavaScript 构建的。这意味着它只是 javascript。

document.getElementById()

document.getElementById()方法返回具有指定值的ID属性的元素,如果不存在具有指定ID的元素,则返回null。ID在页面内应该是唯一的。

Jquery $()

使用 id 选择器作为参数调用 jQuery() 或 $() 将返回一个 jQuery 对象,其中包含零个或一个 DOM 元素的集合。每个 id 值在文档中只能使用一次。如果多个元素被分配了相同的 ID,则使用该 ID 的查询将仅选择 DOM 中第一个匹配的元素。

jQuery is built over JavaScript. This means that it's just javascript anyway.

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.

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

冷心人i 2024-10-07 18:24:02

截至 2019 年,所有答案都是旧的,您可以直接在 javascript 中访问 id 键控字段,只需尝试一下

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

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

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

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

Online Demo!
- https://codepen.io/frank-dspeed/pen/mdywbre

刘备忘录 2024-10-07 18:24:02

以上所有答案都是正确的。如果您想查看它的实际效果,请不要忘记浏览器中有控制台,您可以在其中清晰地看到实际结果:

我有一个 HTML:

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

转到控制台 (cntrl+shift+c) 并使用这些命令清楚地查看结果

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

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

正如我们所看到的,在第一种情况下,我们得到了标签本身(严格来说,是一个 HTMLDivElement 对象)。在后者中,我们实际上没有一个普通的对象,而是一个对象数组。正如上面其他答案所提到的,您可以使用以下命令:

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

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 :

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

Go to console (cntrl+shift+c) and use these commands to see your result clearly

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). 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文