Performing common jQuery tasks in Native JavaScript

April 7, 2018 · Filed under Web Development

I’ve been working on improving my native JavaScript skills lately. Primarily, I’m trying to get away from using jQuery in my day to day coding. It seems like the industry has been moving away from jQuery for quite a while.

I’ve been regularly using a website called PlainJS that provides a lot of additional tips and a more comprehensive view of how to do common jQuery tasks. Below I’ve outlined some of the most helpful for me to get you started. After reading this, refer to the PlainJS site if you want to do a much deeper dive.

Waiting until page is loaded

This is often accomplished in jQuery with:

But is easily substituted with native JavaScript:

Selecting an element

One of the most basic things you need to do when manipulating the DOM is selecting an element. Historically, this was somewhat difficult to do with cross browser support. jQuery uses a selector engine called Sizzle that allows users to select elements with CSS selectors, like so:

var $header = $('.header .container');

In native JS, this is easily accomplished with the document.querySelector() and document.querySelectorAll() methods. You can use those two methods in the same exact way you would in jQuery, for example:

var $header = document.querySelector('.header .container');

It’s quicker. Also, you can select IDs with this method so you don’t have to use the older getElementById You can use querySelectorAll() to return a NodeList with all the matching elements.

Note: jQuery has a list of custom selectors called Selector Extensions that are not part of the CSS spec that are not usable with these native functions.

DOM manipulation

This is the big reason people like jQuery. JavaScript doesn’t have a ton of native, built in functions that replicate the functionality that jQuery provides here, but the same effect can often be accomplished with a small helper function that’s a few lines. This saves you from loading jQuery’s huge (100kb+) library for a few small things.

However, there are a few things we can do. To create an element, simple use document.createElement() and use the innerHTML property to fill it, like so:

var el = document.createElement('section')

el.innerHTML = "Lorem ipsum";

If you want to clone an element, you can use document.cloneNode().

Learn more about native methods and simple helper functions to do DOM manipulation on this section of the PlainJS site.

Daniel Immke

I design and build things for the web from Atlanta, Georgia. I write about topics I encounter in my day to day work here.

Learn more