Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Migrating From jQuery to Vanilla Javascript Discussion

General • Asked by Chris Oliver

`document.querySelectorAll` looks like return an array, but in fact it is an object. It's important to keep this in mind in order to avoid some problems iterating the dom elements.

Hey Felipe,

Yeah, I think I know what you mean. querySelectorAll returns an object but since you can do something like object[0] to get the first element in the object, it looks like you might be working with an array. Great point.


@Chris, I know this episode is a little old, but this is still something I'm dealing with today.

I understand the rationale behind the move to get rid of jQuery in web apps: jQuery was from a time when we needed cross-browser compatability, when vanilla JS didn't provide functionality, that vanilla JS is now good and fast, etc...

And I agree with many of the points.

However, in almost evey project I've written in the last 2 years that doesn't use jQuery, one of the first things I find myself doing is writing a JS class that has a lot of helper functions that look very similar to jQuery.

This is easiest to see with dynamically appending elements to the document using something like Rails' <action>.js.erb format.

Writing this:

const fragment = document.createRange().createContextualFragment("<%= j render(partial: '...') %>")

document.querySelector("#some-selector").appendChild(fragment)

Seems a lot more painful than this:

$("#some-selector").append("<%= j render(partial: '...') %>")

I end up writing a class like the below where I throw in all my helper functions, essentially mimicking jQuery:

# JS helper class attached to window.Global (using webpack)
export default class Global {
  static append(selector, html) {
    const fragment = document.createRange().createContextualFragment(html)
    document.querySelector(selector).appendChild(fragment)
  }
}

I understand if someone is using a framework like React/Angular/VueJS then they wouldn'd use jQuery, but that's because they're using another framework which abstracts complexity.

Do you find that you and other developers are writing your own helper functions to abstract some of the complexity of vanilla JS away? How do you handle trying to write less code that is easier to maintain with the move away from jQuery?


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,242+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.