jQuery vs document.querySelectorAll

后端 未结 12 1105
闹比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:47

    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.

提交回复
热议问题