#218 From jQuery to ES6


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 - http://youmightnotneedjquery.com/ 


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 = $('li.blue')

// ES6
const lead = document.getElementById('lead')
const firstRedItem = document.querySelector('.red')
const blueListItems = document.querySelectorAll('li.blue')
Custom Selector Functionfunction $(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 [].slice.call(results)

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!');

Rocela Durazo Verdugo PRO said about 1 month ago on From jQuery to ES6 :

great episode, what vs code plugin you have for autocomplete ES6?

kobaltz PRO said about 1 month ago on From jQuery to ES6 :

I actually don't have any JS specific plugins. The only real plugins I have which adds functionality are Gitlens, Ruby, and Ruby Solargraph.

Rocela Durazo Verdugo PRO said about 1 month ago on From jQuery to ES6 :

Ok, thanks :-)

Login to Comment