Appendix B. Native equivalents of common jQuery functionality
In chapter 8, I discussed the importance of embracing minimalism in your website’s JavaScript. A way of getting there is to drop jQuery altogether and use what’s available in the browser. This appendix highlights some common jQuery functions and then shows you how to accomplish the same tasks by native means. This isn’t a complete reference. Such a thing would be far beyond the scope of an appendix. This is to get you started.
jQuery’s core $ method selects DOM elements by using a CSS selector string like so:
This selects all <div> elements on a page. Generally speaking, whatever valid CSS selector that works in the $ method will work with document.querySelector and document.querySelectorAll (excluding any custom selectors specific to jQuery). The difference between them is document.querySelector returns only the first matching element, whereas document.querySelectorAll returns all matched elements in an array object, even if only one element is returned. This listing shows examples, with return values annotated.
Although these two methods are useful, other methods are more widely supported and are faster when it comes to selecting elements. They’re shown in table B.1.