From jQuery to ES6

Episode #218 by Teacher's Avatar David Kimura


jQuery has been a great tool for many years, but we've seen a transition in the past years where applications have dropped jQuery and moved to vanilla javascript. In this episode, we look at some common jQuery examples and the ES6 equivalencies.
javascript es6 jquery 10:57


You might not need jQuery - 


# Selectors
<div id="lead">lorem ipsum</div>

  <li class="blue">First item</li>
  <li class="red">Second item</li>
  <li class="blue">Third item</li>
  <li class="red">Last item</li>
<p class="blue status">A great status</p>

// JQuery
var lead = $('#lead');
var firstRedItem = $('.red').eq(0);
var blueListItems = $('')

// ES6
const lead = document.getElementById('lead')
const firstRedItem = document.querySelector('.red')
const blueListItems = document.querySelectorAll('')

# Custom Selector Function
function $(selector, context) {
  var context = context || document
  var selectorType = 'querySelectorAll'
  var is_single_element = selector.indexOf('#') === 0

  if (is_single_element) {
    selectorType = 'getElementById'
    selector = selector.substr(1, selector.length)

  var results = context[selectorType](selector)

  if (is_single_element) {
    return results
  } else {
    return []


# Inserting into the DOM
<div id="comments">  
  <p class="comment">First!</p>
  <p class="comment">Enough with that!</p>

  <textarea id="commentContent"></textarea>
  <button>Post comment</button>

// JQuery
var commentContent = $('#commentContent').val()
$('#comments').append('<p class="comment">' + commentContent + '</p>')

// ES6
const commentContent = document.getElementById('commentContent').value
const comments = document.getElementById('comments')
comments.insertAdjacentHTML('beforeend', `<p class="comment">${commentContent}</p>`)

# Modifying Classes
// JQuery

// ES6
// selected by getElementById or querySelector

// selected by querySelectorAll
elements.forEach((element) => {

# Event Listeners
<button id="btn">Click me!</button>

// With jQuery, we would use the .on() method (or one of its shortcuts):

$('#btn').on('click', function(event) {  
  alert('Thanks for clicking!');

// The modern DOM gives you addEventListener to play with:

const button = document.getElementById('btn');
button.addEventListener('click', (event) => {  
  alert('Thanks for clicking!');