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.

You might not need jQuery – http://youmightnotneedjquery.com/ 

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

<ul> <li class="blue">First item</li> <li class="red">Second item</li> <li class="blue">Third item</li> <li class="red">Last item</li> </ul> <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 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 [].slice.call(results)
  }
}

$('#lead')
$('input[type=text]')
$('textarea')
# Inserting into the DOM
<div id="comments">  
  <p class="comment">First!</p>
  <p class="comment">Enough with that!</p>
</div>

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

// 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
$(selector).addClass('bold');
$(selector).removeClass('bold');
$(selector).toggleClass('bold');

// ES6
// selected by getElementById or querySelector
element.classList.add('bold')
element.classList.remove('bold')
element.classList.toggle('bold')

// selected by querySelectorAll elements.forEach((element) => { element.classList.add('bold') })
# 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!');
});