[javascript] jQuery vs document.querySelectorAll

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.

So the question is this: why 'risk' jQuery's overhead if its strongest asset can be achieved with pure JavaScript?

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!

Any thoughts?

This question is related to javascript jquery html css-selectors jquery-selectors

The answer is


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.

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

I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.

                    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.

http://youmightnotneedjquery.com/


Appendix: Further speed comparisons how native methods compete to jquery


That's because jQuery can do much more than querySelectorAll.

First of all, jQuery (and Sizzle, in particular), works for older browsers like IE7-8 that doesn't support CSS2.1-3 selectors.

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.

And it does it cross-browsers, flawlessly, offering all that jQuery can offer (plugins and APIs).

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.


as the official site says: "jQuery: The Write Less, Do More, JavaScript Library"

try to translate the following jQuery code without any library

$("p.neat").addClass("ohmy").show("slow");

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.

jQuery:

$('.my-class').hide();

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.


Just a comment on this, when using material design lite, jquery selector does not return the property for material design for some reason.

For:

<div class="logonfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="myinputfield" required>
        <label class="mdl-textfield__label" for="myinputfield">Enter something..</label>
      </div>

This works:

document.querySelector('#myinputfield').parentNode.MaterialTextfield.change();

This does not:

$('#myinputfield').parentNode.MaterialTextfield.change();

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.

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.

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.

To sum up, I see the main benefits of jQuery as being concise code, and ubiquity.


To understand why jQuery is so popular, it's important to understand where we're coming from!

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

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.

Now, more than a decade later, a lot of features that made jQuery so popular have become included in the javaScript standard:

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.

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!


Old question, but half a decade later, it’s worth revisiting. Here I am only discussing the selector aspect of jQuery.

document.querySelector[All] is supported by all current 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).

Therefore when it comes to manipulating an element directly, it is to be preferred over jQuery.

For example:

var element=document.querySelector('h1');
element.innerHTML='Hello';

is vastly superior 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.

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.

Where jQuery has an advantage, however, is in how it handles collections. If the requirement is to set properties of multiple elements, jQuery has a built-in each method which allows something like this:

var $elements=$('h2');  //  multiple elements
$elements.html('hello');

To do so with Vanilla JavaScript would require something like this:

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.

As a rule, I caution against using jQuery for new projects:

  • jQuery is an external library adding to the overhead of the project, and to your dependency on third parties.
  • jQuery function is very expensive, 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.

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.

This makes no mention of other features of jQuery. However, I think that they, too, need a closer look.


I think the true answer is that jQuery was developed long before querySelector/querySelectorAll became available in all major browsers.

Initial release of jQuery was in 2006. In fact, even jQuery was not the first which implemented CSS selectors.

IE was the last browser to implement querySelector/querySelectorAll. Its 8th version was released in 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.


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.

Here's some cherry-pickings from the source that show the kind of things jQuery(w/ Sizzle) sorts out for you:

Safari quirks mode:

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.

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


$("#id") vs document.querySelectorAll("#id")

The deal is with the $() function it makes an array and then breaks it up for you but with document.querySelectorAll() it makes an array and you have to break it up.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css-selectors

Angular 2: How to style host element of the component? How to click a href link using Selenium How do I apply a style to all children of an element How to write a CSS hack for IE 11? :last-child not working as expected? Need to find element in selenium by css jQuery select child element by class with unknown path How do I select an element that has a certain class? What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing? What is the mouse down selector in CSS?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value