Update: many people have asked about browser compatability for the native methods I’ve shown. Here are the links to that information: querySelector/querySelectorAll, classList, getElementsByClassName, createDocumentFragment.

If you checked out my last post you’ll know that I have been doing lots of JavaScript coding as of late, both inside and out of Brackets. I have also been doing a series of performance tests (1, 2, 3) between popular jQuery methods and their native DOM equivalents.

Yes I know what you’re thinking. Obviously native methods are faster because jQuery has to deal with older browsers and host of other things. I completely agree. That’s why this post is not meant at all to be anti-jQuery. But if you are able to target modern browsers in your work, using the native C++ methods provided by your browser will not-surprisingly give you a tremendous performance boost in most areas.

I think there are many developers who don’t realize that most of the jQuery methods they use have native equivalents that require the same or only a slighter larger amount of code to use. Below are a series of code samples showing some popular jQuery functions along with their native counterparts.

Easily being able to find DOM elements is at the core of what jQuery is about. You can pass it a CSS selector string and it will retrieve all of the elements in the DOM that match that selector. For the most part, this can all be easily achieved natively using the same amount of code.

DOM manipulation
Another area where jQuery is used frequently is in manipulating the DOM, by either inserting or removing elements. To do these things properly with native methods, you will definitely have to write some extra lines of code, but of course you can always write your own helper functions to make things like this easier. Below is an example of inserting a set of DOM elements into the body of a page.

CSS classes
It is very easy in jQuery to add, remove, or check for the existence of CSS classes on DOM elements. Luckily it is just as easy to do this with native methods. I only recently found out about these myself. Thanks you Chrome DevTools.

Modifying CSS properties
The need to programmatically set and retrieve CSS properties using JavaScript comes up all the time. When doing this it is much faster to simply set the individual styles one by one rather than passing them all to jQuery’s CSS function. It really isn’t any additional code either.

Remember, jQuery is an amazing library that makes all of our lives easier. But you should always choose to use native DOM methods if they are available to you. This is especially true if you are using jQuery inside of loops or timers.

Now of course, I have been hanging around game developers for a while now so maybe I’m a tad over-sensitive about performance. In that world if your game doesn’t run at 60 FPS, you might as well go work at Target. Anyway, hope this post helps some folks!