loading...
Cover image for From jQuery to JavaScript โ€“ How to make the move ๐ŸŒ 

From jQuery to JavaScript โ€“ How to make the move ๐ŸŒ 

webdeasy profile image WebDEasy Originally published at webdeasy.de ใƒป5 min read

Originally published on webdeasy.de!

Moving from jQuery to JavaScript offers several advantages. Besides removing dead code, you can also increase your website speed for SEO.

You have already made the switch from jQuery to pure JavaScript (also called Vanilla JS), otherwise you probably wouldnโ€™t be here. Thatโ€™s a good start. I was also faced with this decision, so Iโ€™ll try to help you with the switch and show you why itโ€™s worth it and how you can proceed.

I had the hope that there is some kind of โ€œjQuery to JavaScript converterโ€ or something like that online. But I was taught better.

So if you really want to make the move, you have to do it manually. But Iโ€™ll help you make the move.

Improve SEO through Vanilla JavaScript?

Sounds funny at first, but thereโ€™s something to it. Iโ€™m always working on improving this site and the articles. For me โ€“ and also for search engines โ€“ the loading speed of the website is an important key figure.

I like to use web.dev Measure or PageSpeed Insights for testing. In the detailed report you get a detailed list of all problems, including the loading speed.

I had a too high value for the execution time of JavaScript. Now I am very satisfied with it.
JavaScript execution time after the conversion<br>
Also with resources that are loaded my jQuery file appeared additionally. And if you look here, the jQuery file with 11KB is already one of the larger files โ€“ despite being minified.
Resources that block rendering after the change<br>
Donโ€™t get me wrong, I love jQuery โ€“ simply an ingenious library. I have already programmed many great functions, like a Reading Position Indicator with jQuery.

But still I had to ban that from this site โ€“ for SEO and maybe also as a little challenge to deal more with Vanilla JS.

Remove dead code

If you already change something in the structure, you can use the opportunity directly to remove unnecessary and outdated code.

For this I made a list of all functions (there were 11 in total) and assigned a priority to each function.

I started with the important and essential functions and rewrote them in Vanilla JS.

Step by step. If you take over each function individually you might find errors or code that is no longer needed. You can delete them directly.

This will tidy up your new JavaScript file at the same time and it is also directly beneficial to the clarity.

Convert jQuery Code

The site youmightnotneedjquery.com was especially helpful for the conversion to Vanilla JS. There you can compare direct functions in jQuery and JavaScript. I hope that with the help of my and this site you will be able to make the change without problems.

Now comes the announced list, with direct translations to convert jQuery to Vanilla JS

This list consists of the functions I used to switch on this one, partly there are overlaps with functions from the mentioned page.

1:1 jQuery to JavaScript translations

Document Ready Function

The function is called when the page is loaded. Thus, the execution of JavaScript does not block the page from loading.

// with jQuery
$(function() {
  /* ... */
});

// Vanilla JS
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}
ready(() => {
  /* ... */
});

Selecting elements

The biggest difference when selecting elements is that in pure JavaScript you have to create a loop if there are multiple elements. In jQuery, for example, you can register events using the selector and it applies to all of them. More details in the section Event Handling.

// with jQuery
// multiple elements
let buttons = $('button.red-btn');
// one element
let button = $('button.green-btn');

// Vanilla JS
// multiple elements
let buttons = document.querySelectorAll('button.red-btn');
// one element
let button = document.querySelector('button.green-btn');

With parentNode you get the parent element. You can also string the statement together to get elements further up in the DOM โ€“ i.e. parentNode.parentNode.

// with jQuery
let foobarParent = $('#foobar-container').parent();
// Vanilla JS
let foobarParent = document.querySelector('#foobar-container').parentNode;

Event Handling

For event handling you have to look if you have one or more elements. JQuery doesnโ€™t care, it just registers the event. Here is an example for both situations.

// with jQuery
$('.link').click(function() {
  /* ... */
});

// Vanilla JS
// one element
document.querySelector('#link').addEventListener('click', event => {
  /* ... */
});
// more elements
document.querySelectorAll('.link').forEach(link => {
  link.addEventListener('click', event => {
    /* ... */
  });
});

To deregister events the actual event callback function is necessary in Vanilla JS. So if you register an event, you should create it in a separate callback function.

// with jQuery
$('#foobar').off('click');

// Vanilla JS
document.getElementById('foobar').removeEventListener('click', clickEvent);
function clickEvent(event) { }

Performing actions on elements

To achieve show() and hide(), we simply change the CSS property display accordingly.

// with jQuery
$('.foobar').show();

// Vanilla JS
document.querySelectorAll('.foobar').forEach(element => {
  element.style.display = 'block';
});
// with jQuery
$('.foobar').hide();

// Vanilla JS
document.querySelectorAll('.foobar').forEach(element => {
  element.style.display = 'none';
});

Querying and changing attributes of elements

The query and handling of the classes works as easy as with jQuery. Only the spelling is a bit different. If you need a toggleClass() function, you can easily program it yourself.

// with jQuery
if($('.foo').hasClass('bar')) {
  /* ... */
}

// Vanilla JS
if(document.querySelector('.foo').classList.contains('bar')) {
  /* ... */
}
// with jQuery
$('.foo').addClass('bar');

// Vanilla JS
document.querySelector('.foo').classList.add('bar');
// with jQuery
$('.foo').removeClass('bar');

// Vanilla JS
document.querySelector('.foo').classList.remove('bar');

The query of other attributes is also quite similar. Note that sometimes the output is different from the jQuery function.

// with jQuery
console.log($('.foobar').attr('checked')); // Output: checked/undefined

// Vanilla JS
console.log(document.querySelector('.foobar').checked); // Output: true/false
// with jQuery
$('.foobar').html();
$('.foobar').html('<span>Hello world!</span>');

// Vanilla JS
document.querySelector('.foobar').innerHTML;
document.querySelector('.foobar').innerHTML = '<span>Hello world!</span>';

Determine offsets and dimensions

// with jQuery
let offset = $(window).scrollTop();

// Vanilla JS
let offset = window.pageYOffset;
// with jQuery
$(window).width();

// Vanilla JS
parseFloat(getComputedStyle(document.querySelector('html'), null).width.replace("px", ""));
// with jQuery
$('.foobar').width();

// Vanilla JS
document.querySelector('.foobar').offsetWidth;
// with jQuery
$('.foobar').offset().top;

// Vanilla JS
document.querySelector('.foobar').offsetTop;

Styling of elements

For styles that are joined with a hyphen, you can use the Camel Case spelling. For example, justify-content becomes justifyContent.

// with jQuery
$('.foobar').css('display', 'flex');
$('.foobar').css('margin-top', '3rem');
let displayProperty = $('.foobar').css('display');

// Vanilla JS
document.querySelector('.foobar').style.display = 'flex';
document.querySelector('.foobar').style.marginTop = '3rem';
let element = document.querySelector('.foobar');
let elementStyle = getComputedStyle(element, null);
let displayProperty = elementStyle.display;

Create new elements

If you want to create new elements and add them to an element, you can do this as follows.

Individual attributes and classes must be added individually, described in more detail in the section Querying and changing attributes of elements.

// with jQuery
$('.foo').append('<p class="child" id="child-id">bar</p>');

// Vanilla JS
let bar = document.createElement('p');
bar.classList.add('child');
bar.id = 'child-id';
bar.innerHTML = 'bar';
document.querySelector('.foo').appendChild(bar);

This is how the changeover looks in practice

This is most of the features I needed when I switched over.

But I would like to give you exclusively the JavaScript file of this page. Before and after switching to Vanilla JS.

Maybe you can use the one or other line of code. ๐Ÿ™‚

โžก๏ธBoth files can be found in the original post here!๐Ÿ”ฅ

Is it even worth the effort?

In my eyes: Yes! Besides cleaning up my code, I have directly removed unnecessary functions. That makes the visitors of your site happy, too.

Which experience did you made with jQuery or the move from jQuery to JavaScript? Happy to hear about your journeys. ๐Ÿ˜€

Posted on by:

webdeasy profile

WebDEasy

@webdeasy

German Front- & Backend Web Developer. Let us change the world!

Discussion

markdown guide
 

jquery is not just about fetching elements and attaching event handlers. You showed maybe 1% of all jQuery features.

 

I know. And I wrote that this are the function I needed to move my website from jquery to js. I never said that this are all functions ๐Ÿ˜‰

 

I also tried to abandon jquery in my project - Metro 4, from this process I got the - M4Q library ๐Ÿคช

 

He wrote a blog post, not a JavaScript lib for jQuery!