jQuery vs document.querySelectorAll

后端 未结 12 1100
闹比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 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 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.

提交回复
热议问题