WordPress already enqueues jQuery by default. Why not make use of it?
That, I agree. You can disable it but a lot of themes and plugins depend on it. So it’s not an option for most WordPress sites.
However, more and more people are moving away from jQuery. That means a lot of community resources like libraries and StackOverflow questions you found are using native JavaScript.
Being able to understand that and adapt it to your project will be highly beneficial to you. Moreover, it will prepare you to use a modern framework like React or Vue.
So what’s the best way to learn native JS?
Learning Native JavaScript
Check out the website below. It lists out the native equivalent of most jQuery functions.
As you can see, most of them are quite simple. For the complex ones like AJAX and Custom Event, you can create helper functions.
EXAMPLE
Convert the jQuery snippet below into native JS:
// jQuery
// get one element
let $el = $( '.my-div' );
// change the HTML content
$el.html( '<span>Hello World</span>' );
// add class
$el.addClass( 'new-class' );
// JS
let $el = document.querySelector( '.my-div' );
// need to check whether element exists or not
if( $el ) {
$el.innerHTML = '<span>Hello World</span>';
$el.classList.add( 'new-class' );
}
For the second example, we will take a look at multiple elements. This is the biggest inconvenience of native JS. You need to loop each one like shown below:
// jQuery
// get multiple elements
let $cards= $( '.container .card' );
// add click listener to all cards at once
$cards.on( 'click', doSomething );
// JS
let $cards = document.querySelectorAll( '.container .card' );
// Loop and assign the listener to each item
[].forEach.call( $cards, function( $card ) => {
$card.addEventListener( 'click', doSomething );
});
Using ES6 Syntax
Some of the snippets from that website can be shortened using ES6 syntax. It’s not supported by Internet Explorer (IE), but that only covers 1.3% global usage).
The notable ones are:
LOOPING QUERY SELECTOR ALL
// IE9
var $elements = document.querySelectorAll( '.selector' );
Array.prototype.forEach.call( $elements, function( $el ) {
// do something
} );
// ES6
let $elements = document.querySelectorAll( '.selector' );
for( let $el of $elements ) {
// do something
}
MATCHING SELECTOR
// IE9
var matches = function(el, selector) {
return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
};
matches(el, '.my-class');
// ES6
el.matches( '.my-class' );
SIBLINGS SELECTOR
// IE9
var $items = $el.parentNode.children;
var $siblings = Array.prototype.filter.call( $items , function( $item ) {
return $item !== $el;
});
// ES6
let $items= $el.parentNode.children;
let $siblings = [...$items].filter( $item => $item !== $el );
FIND INDEX
// IE9
function index( $el ) {
if (!$el) return -1;
var i = 0;
do {
i++;
} while ( $el = $el.previousElementSibling );
return i;
}
let $el = document.querySelector( '.my-item' );
let elIndex = index( $el );
// ES6
let $el = document.querySelector( '.my-item' );
let elIndex = [...$el.parentNode.children].indexOf( $el );
AJAX / API CALL
// IE10
var request = new XMLHttpRequest();
request.open('GET', '/my/api/url', true);
request.onload = function() {
// Do something with the data
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
console.log( data );
}
// Handle error
else {
throw new Error( this.responseText );
}
};
request.send();
// ES6
fetch( '/my/api/url', { method: 'GET' } )
.then( response => {
if( response.status >= 200 && response.status < 400 ) {
return response.json();
} else {
return Promise.reject( response.statusText );
}
} )
// Do something with the data
then( data => {
console.log( data );
} )
// Handle error
.catch( err => {
throw new Error( err );
} );
ES5 version uses a slick Promise object but it’s as long as the old one. So I recommend creating a helper function as shown in this Gist.
Now you only need the snippet below to do an API call:
myAPI.get( '/my/api/url' ).then( data => {
// Do something with the data
} );
What’s Next?
- Practice makes perfect! Try converting one of your projects that uses jQuery into native JS. Do it little by little and keep testing so that the functionality stays the same.
- Learn how to use Webpack.
- Learn a modern framework like Vue. I recommend these tutorials from Academind.
Conclusion
It’s fine to use jQuery. But don’t use it on a large scale project.
jQuery is naturally disorganized. So if you need to create a rather complex and interactive feature, use a proper library like Vue or React.
Don’t repeat my mistake. I had to rewrite a jQuery app I made 3 years ago into Vue because it’s getting very difficult to maintain and update.
As always, leave your question in the comment section below 🙂
Hello. You have introduced some blocks of code by "// ES5", but it should be "// ES6" (or more exactly ES6+). ES5 is the old version of ECMA standard, which is fully supported by e.g. Internet Explorer.
Thanks for noticing! I will revise my article