jQuery vs document.querySelectorAll

后端 未结 12 924
闹比i
闹比i 2020-11-28 01:28

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

相关标签:
12条回答
  • 2020-11-28 01:50

    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.

    0 讨论(0)
  • 2020-11-28 01:50
    $("#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.

    0 讨论(0)
  • 2020-11-28 01:52

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

    0 讨论(0)
  • 2020-11-28 02:02

    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");
    
    0 讨论(0)
  • 2020-11-28 02:03

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

    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 compatible way or the ajax interface.

    If you only want the selector engine from jQuery you can use the one jQuery itself is using: Sizzle That way you have the power of jQuerys Selector engine without the nasty overhead.

    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.

    Of course you have to be disciplined to not write jQuery like this:

    $('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:

    1) Find the element, consider taking all element or only the first.

    // $('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!)

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

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

    0 讨论(0)
  • 2020-11-28 02:04

    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

    • Array: $.inArray vs Array.indexOf: Jquery 24% slower

    • DOM: $.empty vs Node.innerHtml: Jquery 97% slower

    • DOM: $.on vs Node.addEventListener: Jquery 90% slower

    • DOM: $.find vs Node.queryselectorall: Jquery 90% slower

    • Array: $.grep vs Array.filter: Native 70% slower

    • DOM: $.show/hide vs display none: Jquery 85% slower

    • AJAX: $.ajax vs XMLHttpRequest: Jquery 89% slower

    • Height: $.outerHeight vs offsetHeight: Jquery 87% slower

    • Attr: $.attr vs setAttribute: Jquery 86% slower

    0 讨论(0)
提交回复
热议问题