Javascript jQuery 与 document.querySelectorAll
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11503534/
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
jQuery vs document.querySelectorAll
提问by Joel_Blum
I heard several times that jQuery's strongest asset is the way it queries and manipulates elements in the DOM: you can use CSS queries to create complex queries that would be very hard to do in regular javascript .
However , as far as I know, you can achieve the same result with document.querySelector
or document.querySelectorAll
, which are supported in Internet Explorer 8 and above.
我曾多次听说 jQuery 最强大的资产是它查询和操作 DOM 中元素的方式:您可以使用 CSS 查询来创建在常规 javascript 中很难做到的复杂查询。但是,据我所知,您可以使用document.querySelector
或获得相同的结果,document.querySelectorAll
Internet Explorer 8 及更高版本支持。
So the question is this: why 'risk' jQuery's overhead if its strongest asset can be achieved with pure JavaScript?
所以问题是:如果 jQuery 最强大的资产可以用纯 JavaScript 实现,为什么要“冒险”jQuery 的开销?
I know jQuery has more than just CSS selectors, for example cross browser AJAX, nice event attaching etc. But its querying part is a very big part of the strength of jQuery!
我知道 jQuery 不仅仅是 CSS 选择器,例如跨浏览器 AJAX、漂亮的事件附加等。但它的查询部分是 jQuery 实力的重要组成部分!
Any thoughts?
有什么想法吗?
采纳答案by Christoph
document.querySelectorAll()
has several inconsistencies across browsers and is not supported in older browsersThis probably won't cause any trouble anymore nowadays. It has a very unintuitive scoping mechanismand some other not so nice features. Also with javascript you have a harder time working with the result sets of these queries, which in many cases you might want to do. jQuery provides functions to work on them like: filter()
, find()
, children()
, parent()
, map()
, not()
and several more. Not to mention the jQuery ability to work with pseudo-class selectors.
document.querySelectorAll()
浏览器之间存在一些不一致,并且在旧浏览器中不受支持这现在可能不会再造成任何麻烦了。它有一个非常不直观的作用域机制和其他一些不太好的特性。同样使用 javascript,您在处理这些查询的结果集时会更加困难,在许多情况下您可能想要这样做。jQuery提供的功能像他们的工作:filter()
,find()
,children()
,parent()
,map()
,not()
和几个。更不用说 jQuery 使用伪类选择器的能力了。
However, I would not consider these things as jQuery's strongest features but other things like "working" on the dom (events, styling, animation & manipulation) in a crossbrowser compatibleway or the ajax interface.
但是,我不会认为这些东西是 jQuery 最强大的特性,而是其他东西,比如以跨浏览器兼容的方式或 ajax 界面在 dom(事件、样式、动画和操作)上“工作” 。
If you only want the selector engine from jQuery you can use the one jQuery itself is using: SizzleThat way you have the power of jQuerys Selector engine without the nasty overhead.
如果您只想要来自 jQuery 的选择器引擎,您可以使用 jQuery 本身正在使用的一个:Sizzle这样您就可以拥有 jQuery 选择器引擎的强大功能,而不会产生令人讨厌的开销。
EDIT: Just for the record, I'm a huge vanilla JavaScript fan. Nonetheless it's a fact that you sometimes need 10 lines of JavaScript where you would write 1 line jQuery.
编辑:只是为了记录,我是一个巨大的香草 JavaScript 粉丝。尽管如此,您有时需要 10 行 JavaScript,而您将编写 1 行 jQuery,这是事实。
Of course you have to be disciplined to not write jQuery like this:
当然,您必须遵守纪律,不要像这样编写 jQuery:
$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green').end();
This is extremely hard to read, while the latter is pretty clear:
这非常难以阅读,而后者非常清楚:
$('ul.first')
.find('.foo')
.css('background-color', 'red')
.end()
.find('.bar')
.css('background-color', 'green')
.end();
The equivalent JavaScript would be far more complex illustrated by the pseudocode above:
上面的伪代码说明了等效的 JavaScript 会复杂得多:
1) Find the element, consider taking all element or only the first.
1)找到元素,考虑取所有元素或只取第一个。
// $('ul.first')
// taking querySelectorAll has to be considered
var e = document.querySelector("ul.first");
2) Iterate over the array of child nodes via some (possibly nested or recursive) loops and check the class (classlist not available in all browsers!)
2)通过一些(可能是嵌套或递归)循环遍历子节点数组并检查类(类列表并非在所有浏览器中都可用!)
//.find('.foo')
for (var i = 0;i<e.length;i++){
// older browser don't have element.classList -> even more complex
e[i].children.classList.contains('foo');
// do some more magic stuff here
}
3) apply the css style
3)应用css样式
// .css('background-color', 'green')
// note different notation
element.style.backgroundColor = "green" // or
element.style["background-color"] = "green"
This code would be at least two times as much lines of code you write with jQuery. Also you would have to consider cross-browser issues which will compromise the severe speed advantage(besides from the reliability) of the native code.
这段代码至少是您使用 jQuery 编写的代码行数的两倍。此外,您还必须考虑跨浏览器问题,这会损害本机代码的严重速度优势(除了可靠性之外)。
回答by Pascalius
If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.
如果您正在为 IE8 或更高版本优化您的页面,您应该真正考虑是否需要 jquery。现代浏览器本身就有很多 jquery 提供的资源。
If you care for performance, you can have incredible performance benefits (2-10 faster)using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2
如果您关心性能,则可以使用本机 javascript获得令人难以置信的性能优势(快 2-10):http: //jsperf.com/jquery-vs-native-selector-and-element-style/2
I transformed a div-tagcloud from jqueryto native javascript(IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.
我将 div-tagcloud 从jquery 转换为原生 javascript(兼容 IE8+),结果令人印象深刻。只需一点开销,速度就提高了 4 倍。
Number of lines Execution Time
Jquery version : 340 155ms
Native version : 370 27ms
You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.
你可能不需要 Jquery 提供了一个非常好的概述,其中本机方法替换了哪个浏览器版本。
http://youmightnotneedjquery.com/
http://youmightnotneedjquery.com/
Appendix: Further speed comparisons how native methods compete to jquery
附录:进一步的速度比较本地方法如何与 jquery 竞争
回答by John Slegers
To understand why jQuery is so popular, it's important to understand where we're coming from!
要了解 jQuery 为何如此受欢迎,重要的是要了解我们从何而来!
About a decade ago, top browsers were IE6, Netscape 8 and Firefox 1.5. Back in those days, there were little cross-browser ways to select an element from the DOM besides Document.getElementById()
.
大约十年前,顶级浏览器是 IE6、Netscape 8 和 Firefox 1.5。在那个年代,除了Document.getElementById()
.
So, when jQuery was released back in 2006, it was pretty revolutionary. Back then, jQuery set the standard for how to easily select / change HTML elements and trigger events, because its flexibility and browser support were unprecedented.
因此,当 jQuery于 2006 年发布时,它是非常具有革命性的。当时,jQuery 为如何轻松选择/更改 HTML 元素和触发事件设定了标准,因为它的灵活性和浏览器支持是前所未有的。
Now, more than a decade later, a lot of features that made jQuery so popular have become included in the javaScript standard:
现在,十多年后,许多使 jQuery 如此流行的特性已包含在 javaScript 标准中:
- Instead of jQuery's
$()
, you can now now useDocument.querySelectorAll()
- Instead of jQuery's
$el.on()
, you can now useEventTarget.addEventListener()
- Instead of jQuery's
$el.toggleClass()
, you can now useElement.classList.toggle()
- ...
- 而不是 jQuery's
$()
,您现在可以使用Document.querySelectorAll()
- 而不是 jQuery's
$el.on()
,您现在可以使用EventTarget.addEventListener()
- 而不是 jQuery's
$el.toggleClass()
,您现在可以使用Element.classList.toggle()
- ...
These weren't generally available back in 2005. The fact that they are today obviously begs the question of why we should use jQuery at all. And indeed, people are increasingly wondering whether we should use jQuery at all.
这些在 2005 年普遍不可用。它们今天的事实显然回避了我们为什么应该使用 jQuery 的问题。事实上,人们越来越想知道我们是否应该使用 jQuery。
So, if you think you understand JavaScript well enough to do without jQuery, please do! Don't feel forced to use jQuery, just because so many others are doing it!
所以,如果你认为你对 JavaScript 的了解足以在没有 jQuery 的情况下完成,请这样做!不要因为有太多人在使用 jQuery 而感到被迫使用 jQuery!
回答by KGZM
jQuery's Sizzle selector engine can use querySelectorAll
if it's available. It also smooths out inconsistencies between browsers to achieve uniform results. If you don't want to use all of jQuery, you could just use Sizzle separately. This is a pretty fundamental wheel to invent.
querySelectorAll
如果可用,jQuery 的 Sizzle 选择器引擎可以使用。它还可以消除浏览器之间的不一致以实现统一的结果。如果您不想使用所有 jQuery,您可以单独使用 Sizzle。这是一个非常基本的发明轮子。
Here's some cherry-pickings from the source that show the kind of things jQuery(w/ Sizzle) sorts out for you:
以下是一些来自源代码的精选内容,展示了 jQuery(w/ Sizzle) 为您整理的内容:
Safari quirks mode:
Safari 怪癖模式:
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
If that guard fails it uses it's a version of Sizzle that isn't enhanced with querySelectorAll
. Further down there are specific handles for inconsistencies in IE, Opera, and the Blackberry browser.
如果该守卫失败,它将使用它的 Sizzle 版本,该版本未使用querySelectorAll
. 再往下是 IE、Opera 和 Blackberry 浏览器不一致的特定处理。
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
And if all else fails it will return the result of oldSizzle(query, context, extra, seed)
.
如果所有其他方法都失败,它将返回oldSizzle(query, context, extra, seed)
.
回答by MaxArt
That's because jQuery can do much more than querySelectorAll
.
那是因为 jQuery 可以做的远不止querySelectorAll
.
First of all, jQuery (and Sizzle, in particular), works for older browsers like IE7-8 that doesn't support CSS2.1-3 selectors.
首先,jQuery(尤其是 Sizzle)适用于像 IE7-8 这样不支持 CSS2.1-3 选择器的旧浏览器。
Plus, Sizzle (which is the selector engine behind jQuery) offers you a lot of more advanced selector instruments, like the :selected
pseudo-class, an advanced :not()
selector, a more complex syntax like in $("> .children")
and so on.
此外,Sizzle(它是 jQuery 背后的选择器引擎)为您提供了许多更高级的选择器工具,如:selected
伪类、高级:not()
选择器、更复杂的语法,如 in$("> .children")
等等。
And it does it cross-browsers, flawlessly, offering all that jQuery can offer (plugins and APIs).
它可以跨浏览器,完美地提供 jQuery 所能提供的所有功能(插件和 API)。
Yes, if you think you can rely on simple class and id selectors, jQuery is too much for you, and you'd be paying an exaggerated pay-off. But if you don't, and want to take advantage of all jQuery goodness, then use it.
是的,如果您认为您可以依赖简单的类和 id 选择器,那么 jQuery 对您来说太过分了,您将付出夸张的回报。但是,如果您不这样做,并且想利用 jQuery 的所有优点,请使用它。
回答by Steven
Here's a comparison if I want to apply the same attribute, e.g. hide all elements of class "my-class". This is one reason to use jQuery.
如果我想应用相同的属性,这是一个比较,例如隐藏类“my-class”的所有元素。这是使用 jQuery 的原因之一。
jQuery:
jQuery:
$('.my-class').hide();
JavaScript:
JavaScript:
var cls = document.querySelectorAll('.my-class');
for (var i = 0; i < cls.length; i++) {
cls[i].style.display = 'none';
}
With jQuery already so popular, they should have made document.querySelector() behave just like $(). Instead, document.querySelector() only selects the first matching element which makes it only halfway useful.
jQuery 已经如此流行,他们应该让 document.querySelector() 表现得像 $()。相反, document.querySelector() 只选择第一个匹配的元素,这使得它只有一半有用。
回答by Dom Day
In terms of code maintainability, there are several reasons to stick with a widely used library.
在代码可维护性方面,坚持使用广泛使用的库有几个原因。
One of the main ones is that they are well documented, and have communities such as ... say ... stackexchange, where help with the libraries can be found. With a custom coded library, you have the source code, and maybe a how-to document, unless the coder(s) spent more time documenting the code than writing it, which is vanishingly rare.
主要问题之一是它们有很好的文档记录,并且拥有诸如……说……stackexchange 之类的社区,可以在其中找到有关库的帮助。使用自定义编码库,您拥有源代码,也许还有操作文档,除非编码人员花更多时间记录代码而不是编写代码,这种情况非常罕见。
Writing your own library might work for you, but the intern sitting at the next desk may have an easier time getting up to speed with something like jQuery.
编写自己的库可能对你有用,但坐在隔壁桌的实习生可能更容易掌握 jQuery 之类的东西。
Call it network effect if you like. This isn't to say that the code will be superior in jQuery; just that the concise nature of the code makes it easier to grasp the overall structure for programmers of all skill levels, if only because there's more functional code visible at once in the file you are viewing. In this sense, 5 lines of code is better than 10.
如果你愿意,可以称之为网络效应。这并不是说代码在 jQuery 中会更好;只是因为代码的简洁性使所有技能水平的程序员更容易掌握整体结构,因为您正在查看的文件中可以同时看到更多的功能代码。从这个意义上说,5 行代码优于 10 行。
To sum up, I see the main benefits of jQuery as being concise code, and ubiquity.
总而言之,我认为 jQuery 的主要优点是代码简洁,而且无处不在。
回答by simon xu
as the official site says: "jQuery: The Write Less, Do More, JavaScript Library"
正如官方网站所说:“jQuery:少写,多做,JavaScript 库”
try to translate the following jQuery code without any library
尝试在没有任何库的情况下翻译以下 jQuery 代码
$("p.neat").addClass("ohmy").show("slow");
回答by Vanuan
I think the true answer is that jQuery was developed long before querySelector/querySelectorAll
became available in all major browsers.
我认为真正的答案是 jQuery 早querySelector/querySelectorAll
在所有主要浏览器都可用之前就被开发出来了。
Initial release of jQuery was in 2006. In fact, even jQuery was not the first which implemented CSS selectors.
jQuery 的初始版本是在 2006 年。事实上,即使是 jQuery也不是第一个实现 CSS 选择器的。
IE was the last browserto implement querySelector/querySelectorAll
. Its 8th version was released in 2009.
IE 是最后一个实现querySelector/querySelectorAll
. 它的第 8 个版本于 2009 年发布。
So now, DOM elements selectors is not the strongest point of jQuery anymore. However, it still has a lot of goodies up its sleeve, like shortcuts to change element's css and html content, animations, events binding, ajax.
所以现在,DOM 元素选择器不再是 jQuery 的最强点了。然而,它仍然有很多好东西,比如改变元素的 css 和 html 内容的快捷方式、动画、事件绑定、ajax。
回答by Manngo
Old question, but half a decade later, it's worth revisiting. Here I am only discussing the selector aspect of jQuery.
老问题,但五年后,值得重新审视。这里我只讨论jQuery的选择器方面。
document.querySelector[All]
is supported by allcurrent browsers, down to IE8, so compatibility is no longer an issue. I have also found no performance issues to speak of (it was supposed to be slower than document.getElementById
, but my own testing suggests that it's slightly faster).
document.querySelector[All]
所有当前浏览器都支持,下至 IE8,因此兼容性不再是问题。我也没有发现任何性能问题(它应该比 慢document.getElementById
,但我自己的测试表明它稍微快一些)。
Therefore when it comes to manipulating an element directly, it is to be preferred over jQuery.
因此,在直接操作元素时,它比 jQuery 更受欢迎。
For example:
例如:
var element=document.querySelector('h1');
element.innerHTML='Hello';
is vastlysuperior to:
是大大优于:
var $element=$('h1');
$element.html('hello');
In order to do anything at all, jQuery has to run through a hundred lines of code (I once traced through code such as the above to see what jQuery was actually doing with it). This is clearly a waste of everyone's time.
为了做任何事情,jQuery 必须运行一百行代码(我曾经跟踪过类似上面的代码,以查看 jQuery 实际使用它做什么)。这显然是在浪费大家的时间。
The other significant cost of jQuery is the fact that it wraps everything inside a new jQuery object. This overhead is particularly wasteful if you need to unwrap the object again or to use one of the object methods to deal with properties which are already exposed on the original element.
jQuery 的另一个重要成本是它将所有内容都包装在一个新的 jQuery 对象中。如果您需要再次解开对象或使用对象方法之一来处理已在原始元素上公开的属性,则这种开销尤其浪费。
Where jQuery has an advantage, however, is in how it handles collections. If the requirement is to setproperties of multiple elements, jQuery has a built-in each
method which allows something like this:
然而,jQuery 的优势在于它处理集合的方式。如果需要设置多个元素的属性,jQuery 有一个内置each
方法,它允许这样的事情:
var $elements=$('h2'); // multiple elements
$elements.html('hello');
To do so with Vanilla JavaScript would require something like this:
要使用 Vanilla JavaScript 做到这一点,需要这样的东西:
var elements=document.querySelectorAll('h2');
elements.forEach(function(e) {
e.innerHTML='Hello';
});
which some find daunting.
有些人觉得这令人生畏。
jQuery selectors are also slightly different, but modern browsers (excluding IE8) won't get much benefit.
jQuery 选择器也略有不同,但现代浏览器(不包括 IE8)不会获得太多好处。
As a rule, I caution against using jQuery for newprojects:
通常,我警告不要在新项目中使用 jQuery :
- jQuery is an external library adding to the overhead of the project, and to your dependency on third parties.
- jQuery function is veryexpensive, processing-wise.
- jQuery imposes a methodology which needs to be learned and may compete with other aspects of your code.
- jQuery is slow to expose new features in JavaScript.
- jQuery 是一个外部库,增加了项目的开销,并增加了您对第三方的依赖。
- jQuery 函数在处理方面非常昂贵。
- jQuery 强加了一种需要学习的方法论,并且可能会与代码的其他方面产生竞争。
- jQuery 在 JavaScript 中公开新功能的速度很慢。
If none of the above matters, then do what you will. However, jQuery is no longer as important to cross-platform development as it used to be, as modern JavaScript and CSS go a lot further than they used to.
如果以上都不重要,那就做你想做的。然而,jQuery 对跨平台开发不再像过去那样重要,因为现代 JavaScript 和 CSS 比以前走得更远。
This makes no mention of other features of jQuery. However, I think that they, too, need a closer look.
这没有提及 jQuery 的其他功能。但是,我认为他们也需要仔细研究。