DEV Community

loading...
Cover image for From jQuery to JavaScript – How to make the move 🌠

From jQuery to JavaScript – How to make the move 🌠

webdeasy.de
Developer, what else?
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(() => {
  /* ... */
});
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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 => {
    /* ... */
  });
});
Enter fullscreen mode Exit fullscreen mode

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) { }
Enter fullscreen mode Exit fullscreen mode

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';
});
Enter fullscreen mode Exit fullscreen mode
// with jQuery
$('.foobar').hide();

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

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')) {
  /* ... */
}
Enter fullscreen mode Exit fullscreen mode
// with jQuery
$('.foo').addClass('bar');

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

// Vanilla JS
document.querySelector('.foo').classList.remove('bar');
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
// with jQuery
$('.foobar').html();
$('.foobar').html('<span>Hello world!</span>');

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

Determine offsets and dimensions

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

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

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

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

// Vanilla JS
document.querySelector('.foobar').offsetTop;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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. πŸ˜€

Discussion (15)

Collapse
olton profile image
Serhii Pimenov

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

Collapse
webdeasy profile image
webdeasy.de Author

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 πŸ˜‰

Collapse
olton profile image
Serhii Pimenov

I also tried to abandon jquery in my project - Metro 4, from this process I got the - M4Q library πŸ€ͺ

Thread Thread
soumendudas22 profile image
soumendudas22

Never heard of M4Q, just saw it has a weekly download of 1!

Collapse
gijovarghese profile image
Gijo Varghese

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

Collapse
silvervision profile image
Silver vision

Yes this is possible to convert jquery to javascript but its very difficult to manage everything in javascript.I also try a lot to convert it at the end i found one online tool that convert jquery to javascript easily.The tool is workversatile.com
workversatile.com/jquery-to-javasc...

Collapse
webdeasy profile image
webdeasy.de Author

I tried two codes snippets, but it doesn't seem to work....
If that really works, it would be insane!

Collapse
silvervision profile image
Silver vision

Can you please give me your snppets?

Thread Thread
webdeasy profile image
webdeasy.de Author

I tried this:

$('p').click(function() {
alert('test');
});
Enter fullscreen mode Exit fullscreen mode

It gives me the same output.. :c

Thread Thread
silvervision profile image
Silver vision

What is p?
Id or class so please # or . Before p and try.

Thread Thread
webdeasy profile image
webdeasy.de Author

That's working, great!
But p oder h2 or something like that should work. This selects all p (or h2) on the page

Thread Thread
silvervision profile image
Silver vision

Yes its correct i will contact owner of this tool and reply here.

Thread Thread
webdeasy profile image
webdeasy.de Author

I will test it more, but it already looks good

Collapse
soumendudas22 profile image
soumendudas22

What I feel is jQuery and JS both are good only if someone wants to write less code picks jQuery(or if the project is already written in jQuery xD) else vanilla JS.
For me I prefer JS more than jQuery.

Collapse
webdeasy profile image
webdeasy.de Author

Absolutely. It always depends on the project.

Forem Open with the Forem app