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.

B.1. Selecting elements

jQuery’s core $ method selects DOM elements by using a CSS selector string like so:

$("div");

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.

Listing B.1. Using querySelector and querySelectorAll

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.

B.2. Checking DOM readiness

B.3. Binding events

B.4. Iterating over a set of elements

B.5. Manipulating classes on elements

B.6. Accessing and modifying styles

B.7. Getting and setting attributes

B.8. Getting and setting element contents

B.9. Replacing elements

B.10. Hiding and showing elements

B.11. Removing elements

B.12. Going further