Codementor Events

You probably don't need to use jQuery

Published Sep 26, 2018

Ok, jQuery is a very powerful library that makes most of your life easier but... most of the time I saw that I ended up using it just for using CSS selectors in Javascript code. IE6 is long dead, not bothering our lives anymore, so we can just focus in building beautiful software that just runs everywhere (or almost).

After ES6, things have become much easier for us to use Pure JS, and avoid having bloated dependencies on our projects, and having slightly faster page loads.

CSS selectors in pure JS

Everyone should be used to the good and old document.getElementById() method that exists since ever. Not everyone is aware of this, though:

document.querySelector('.myClass li') 

It's a method that exists in close to all the current browsers. Yes, you can use CSS selectors in pure javascript too. It fetches one element, according to any selector you provide. Handy, but... you probably want to select all the elements that match that selection. It's easy too:

document.querySelectorAll('.myClass li') 

This is very straightforward, but works a bit differently than $('.myClass li'), though. While in jQuery you'd start changing the attributes of your list of selected items straight away, with Pure JS you need to explicitly iterate over the return of the function with a for loop since the function now returns a NodeList.

Events and $(document).ready()

This one is very easy to substitute. It's like this:

document.addEventListener("DOMContentLoaded", function() {
  //do stuff
}

the function is "addEventListener", and it works just as you'd expect. The anonymous function is triggered when the event is fired.

Using a combination of these two techniques you can give for example all the buttons the same behaviour: first select them all with document.querySelector, then iterate over each element of the list and add each of them an event with the method element.addEventListener(). Easy.

Discover and read more posts from Sal Sousa
get started
post commentsBe the first to share your opinion
Show more replies