Migrating From jQuery to Vanilla Javascript

May 23, 2017

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Without jQuery in Rails 5.1, we explore what it takes to convert your traditional jQuery code into vanilla Javascript methods

Notes

Selecting elements

// jQuery version
$("#notifications")

// Javascript version
document.querySelector("#notifications") // returns the first matching element
document.querySelectorAll("#notifications a") // returns an array of elements

document.getElementById("notifications") // returns a single element
document.getElementsByTagName("a") // returns an array of elements

document.querySelector("#notifications").querySelectorAll("a") // returns an array of sub-elements from the first query

Adding Event Listeners

// jQuery version
$("a").on("click", function(event) { 
  event.preventDefault()
  console.log("clicked") 
})

// Javascript version
document.querySelectorAll.forEach(function(item) {
  item.addEventListener("click", function(event) {
    event.preventDefault()
    console.log("clicked")
  })
})

Hiding Elements

// jQuery version
$("#notifications").hide()
$("#notifications").show()

// Javascript version
document.querySelector("#notifications").style.display = 'none'
document.querySelector("#notifications").style.display = ''

Appending an element

// jQuery version
$("#notifications").append("<p>New notification</p>")

// Javascript version
node = document.createRange().createContextualFragment("<p>New notification</p>")
document.querySelector("#notifications").appendChild(node)

Retrieving Attributes and Data Attributes

// jQuery version
$("element").attr("attribute")
$("element").data("id")

// Javascript version
document.querySelector("element").getAttribute("attribute")
JSON.parse(document.querySelector("element").getAttribute("data-id"))
// or 
JSON.parse(document.querySelector("element").dataset.id)

AJAX requests

// jQuery version
$.ajax({
  url: "/notifications.json",
  type: "GET",
  success: function(data) {
    console.log(data)
  }
})

// Javascript version (with Rails UJS)
// This automatically includes your CSRF token for non-GET requests as well
Rails.ajax({
  url: "/notifications.json",
  type: "GET",
  success: function(data) {
    console.log(data)
  }
})

Document Event Handlers

// jQuery version
$(document).on("turbolinks:load", function() {
  // initialize code
})

// Javascript version
document.addEventListener("turbolinks:load", function() {
  // initialize code
})

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.