10++ great JS Methods as a replacement for jQuery

10 great JS Methods as a replacement for jQuery

This post covers the top 10++ great JS Methods as a replacement for jQuery. We all wrote some jQuery in our careers. But we don’t need to do that anymore.

Introduction

We have all worked on at least one project where we used jQuery. It was a popular library developed in 2006, and people are still using it because it’s handy or they are used to working with it, but also because a lot of other libraries or front-end frameworks are dependent on it. In this post we are going to go through some of the most used jQuery functions and how we can easily replace them with vanilla javascript functions.

What is jQuery and what is it used for?

jQuery is a library that was developed back in 2006, mostly for DOM manipulation, creating animations, and more dynamic applications. As of Aug 2022, jQuery is used by 77% of the 10 million most popular websites. To get a bigger picture, React is one of the most popular libraries today and it’s used only 3.4% of websites according to W3Techs.

Well, we got to agree that for a library this is a lot! And just to make things clear, although I am not a fan of jQuery, I have a huge respect for its creators. And it does make our lives easier, but is it needed?

What I am trying to say is, do we need jQuery for every website that we create or every application? I don’t think so! Javascript has seen many improvements since 2006 when jQuery was created, and we got a lot of new features that we don’t have in jQuery. Not to mention that CSS has also been improved!

So combining the new features from JavaScript and the CSS we can do a lot of great things without using jQuery.

jQuery document-ready JS alternative

One of the most used jQuery methods that I’ve seen on all the projects I worked on is jQuery(document).ready() method. It’s used to check if the DOM has been fully loaded.

The method uses a callback function, that’s going to be called when the DOM is ready as the method name says. So it’s pretty self-explanatory.

jQuery(document).ready(function() {
	// Write the code for the application here
});

Then in that callback, we are writing the code for our application, knowing that the elements we are looking for are fully loaded. While this is one of the most used jQuery methods out there we can use the load event in vanilla JavaScript to accomplish the same thing.

window.addEventListener("load", (event) => {
  console.log("page is fully loaded");
});

The above code uses a window object and adds the listener of the load event to that object. The addEventListener method also uses a callback function to run immediately after the page has been fully loaded so we have access to all the elements on that page and we can execute our code.

Warning! 

However, this listener will be executed after the page is fully loaded! Including the images, styles, etc!

Waiting only for DOM to Load

If your code doesn’t work with those dependencies, you can use the DOMContentLoaded event to wait only for the DOM to be fully loaded without dependent resources. Let’s take a look at the code below.

document.addEventListener("DOMContentLoaded", (event) => {
  console.log("DOM fully loaded and parsed");
});

It uses the same addEventListener function. We also have the callback function to write our code inside where we know that the DOM is parsed and fully loaded. The only difference between the two is the object to which we are attaching the event listener. In the first case, we are adding the listener to the window object, and in the second example, we are adding the listener to the document object instead.

Getting the elements

For every project that you are creating with JavaScript, you will need to manipulate the DOM. Therefore you will need to get the elements, change them, or even remove them. We are going to explore how you can do that with jQuery and then I am going to show you how to do it with vanilla JS.

$('.row')
$('#container')
$('input[name="username"]')

This is how you can get the elements with jQuery by using the class, id, or name of the input. You can achieve the same thing by using the following code with vanilla JS using the querySelector like so:

document.querySelectorAll('.row');
document.querySelector('#container');
document.querySelector('input[name="username"]');

Just to note that with the querySelector you can write any CSS selector that you want, unlike the getElementById or getElementsByClassName methods. If you would like to learn more about DOM manipulation, read this.

Just note that if you are using a jQuery selector like the one shown above, you need also to use jQuery each method, to loop through them, while with querySelector you can use the forEach method. Check this post where I go more in-depth with array map and filter methods.

jQuery find method alternative

Bonus tip! In addition to a document object, you can call the query selector on any other element that you grabbed before, thus rendering the jQuery find method obsolete. So instead of doing the following:

const myContainer = $('#container');
myContainer.find('.row');

You can get those rows like this:

const myContainer = document.querySelector('#container');
myContainer.querySelectorAll('.row');

We are calling querySelectorAll when we want to get all the elements with the specific class name for example. While calling querySelector with some class you are going to get only the first one that matches, so be careful there!

Adding and changing DOM elements

While getting the elements is important and we are doing it all the time, the other part is to add the elements to the DOM. Whether we got them from the server or we created them in our JS file, using jQuery you can insert them with html method.

JS alternative to the jQuery html() method

$("#output").html('some HTML code');

An alternative to this method can be one of the following vanilla js methods:

documentQuerySelector('#output').innerHTML = 'some HTML code here';
 
documentQuerySelector('#output').insertAdjacentHTML(
    'beforebegin',
    "<strong>inserted text</strong>"
);

The first one will replace the inner HTML code of the element while the other one will insert the HTML code in the position of the user’s choosing. The available positions described by MDN are:

<!-- beforebegin -->
<p><!-- afterbegin -->
  foo
  <!-- beforeend -->
</p><!-- afterend -->

So this code can be a replacement for append and prepend methods too, since you can choose exactly where you want your new element to be placed.

Warning! 

All three of the methods above have a security flaw! They are not sanitizing the elements that you are adding to the page. Meaning that someone can insert the annoying alert call, that will be executed each time when DOM is parsed. So don’t use those when you are working with user inputs or elements that came from a source you don’t trust.

jQuery text() method alternative

While the previous methods are changing the DOM by adding whole HTML elements, we can also add only the text to the element, this approach doesn’t require sanitizing the content that you want to insert into the DOM, thus it’s much safer.

$('#myAwesomeTitle').text('The Iron Man is the best superhero');

To achieve the same result can be achieved by using the following code

documentQuerySelector('#myAwesomeTitle').innerText = 'The Iron Man is the best superhero';

While this is the same there is one more alternative and textContent but first read the warning:

Warning! 

Setting innerText on a node removes all of the node’s content and replaces them with the given string value. Meaning you are going to replace everything within the HTML tags.

While it’s simpler textContent can set text to script and style elements while innerText is used only for the human-readable elements.

The textContent property returns every element in the node and it can be used on hidden elements while innerText is “aware” of styling and won’t return hidden elements.

Being aware of styling innerText triggers reflow to ensure that all the styles are up to date, therefore it’s slower than textContent.

Creating event listeners

To make your applications dynamic you’ll need to listen to the user events, click events, change events, key-up events, etc. Let’s see how we can use some of those events in jQuery and how we can write the same code only with vanilla JS.

jQuery click() method alternative

$('#mySpecialButton').click(function(e) {method
	// Do something when the button has been clicked.
});

If you want to achieve the same thing using vanilla JS, you can use the addEventListener method, paired with the query selector that we have already covered in the previous section.

document.querySelector('#mySpecialButton').addEventListener('click', () => {
	// Do something when the button has been clicked.
});

jQuery on() method alternative

While the click method is separated, in jQuery you can listen for the click and the other events using the on method.

$('#mySpecialButton').on('click',function(e) {
	// Do something when the button has been clicked
});

$('input[name="username"]').on('keyup',function(e) {
	// Do something when the username is changing
});

$('#super-hero-select').on('change',function(e) {
	// Do something when the select value change
});

An alternative for the on and the click methods in vanilla JS is addEventListener, pretty straightforward, one method to rule them all! 🙂

document.querySelector('#mySpecialButton').addEventListener('click', (e) => {
	// Do something when the button has been clicked
});

document.querySelector('input[name="username"]').addEventListener('keyup', (e) => {
	// Do something when the username is changing
});

document.querySelector('#super-hero-select').addEventListener('change', (e) => {
	// Do something when the select value change
});

That’s how you can create the same events with vanilla JS without using jQuery. Also, jQuery for some reason still uses the “old” function syntax for all of the callbacks even in their documentation. I don’t know why, maybe it’s a scope thing, anyway if you would like to read something more about writing better JavaScript code, check out this post.

Animations & Effects

When jQuery was invented CSS was not as powerful at the time as it is now. And using methods like fadeIn, fadeOut, or toggle was useful. Nowadays we have transition in CSS and its simple syntax makes it easy to use.

Working with CSS classes

These are the most used methods in my projects. Whether you are doing some validations, or you are creating animations, you will need these methods. Let’s see how is it done with jQuery and then we will check out alternatives in vanilla JS.

jQuery addClass method alternative

$('#container').addClass(className);

While in vanilla JavaScript we can do the same thing by using add method on the classList property:

document.querySelector('#container').classList.add(className);

jQuery removeClass method alternative

To remove the class in jQuery we can utilize the removeClass method like so:

$('#container').removeClass(className);

while in vanilla javascript we can do the following:

document.querySelector('#container').classList.remove(className);

Also here we are using the classList property but we are using the remove method on it, and we provide it the class which we want to remove.

Replacing CSS class with JavaScript

While vanilla JavaScript has a dedicated method that we can use for this task. jQuery doesn’t! You can only chain the methods together to achieve this:

$("p").removeClass("myClass").addClass("yourClass");

and the vanilla JavaScript method that I like to use is called replace and we can call it on the classList property like this:

document.querySelector("p").classList.replace("foo", "bar");

You will see it shortly in action below!

An alternative to the jQuery fadeIn method

You can achieve the fade-in effect with jquery by writing the following

$('#marvel_heros_row').fadeIn();

while in vanilla JavaScript you could accomplish the same thing by mixing it up with some CSS, firstly you can replace the CSS class with some other animation CSS class that you already have defined by using replace method on the classList property like so

document.querySelector('#marvel_heros_row').classList.replace('hide', 'show');

secondly, in the CSS code, you need to define the classes that you are using

.show {
  transition: opacity 500ms;
}

.hide {
  opacity: 0;
}

and that’s it you successfully animated an element! Fade-out animation can be created as a fade-in. Switch the classes that we used above by writing:

document.querySelector('#marvel_heros_row').classList.replace('show', 'hide');

This will replace the show class with the hide class.

An alternative to the jQuery toggle method

Hiding and showing elements was always part of the websites. To toggle the element with jQuery you could use the toggle method below:

$('#para').toggle();

while in vanilla js you can toggle it like this:

document.querySelector('button').addEventListener('click', () => {
 toggle(document.querySelector('#para'));
});

function toggleElement(el) {
  if (el.style.display === 'none') {
    el.style.display = '';
  } else {
    el.style.display = 'none';
  }
}

Sending AJAX requests

As I said a couple of times now jQuery was developed when JavaScript wasn’t as powerful as today. Back in the day if you wanted to use Ajax you would need to use XMLHttpRequest a.k.a XHR for short.

For me, it’s too complicated to use and I was also using the jQuery Ajax method that was a lot more simple.

But nowadays we have the fetch() API that we can use for these purposes as well as async and await, which made our lives much easier.

To send a post request using jQuery we can use the following

$.ajax({
  type: 'POST',
  url: '/my/url',
  data: data
});

however, if you want to use vanilla JavaScript you can achieve the same thing by utilizing fetch API paired with the await

await fetch('/my/url', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
});

or without it:

fetch('/my/url', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then((response) => {
  if (response.status === 200) {
    return response.json();
  } else {
    throw new Error("Something went wrong on API server!");
  }
})
.then((response) => {
  console.debug(response);
  // …
})
.catch((error) => {
  console.error(error);
});

Working with Arrays

This is a topic in itself. But I’ve chosen some of the most used jQuery methods and those that I use in my projects.

The JS alternative to jQuery isArray method

To check if the variable is an array in jquery you can use the following code

$.isArray(arr);

while in js you can use the isArray from the Array object

Array.isArray(arr);

This can come in handy when you need to do some array-only operations like a map or forEach and you need to make sure that you are working with the array.

jQuery map method JS alternative

Looping through an array of elements and changing it or doing something with a single element is important to do something like that in jQuery you can write:

$.map(array, function (value, index) {});

While to achieve the same thing in javascript you can utilize the widely used js map method

array.map((value, index) => {
	// Do something with the value 
});

If you want to know more about the map check out this post.

The JS alternative to the jQuery toArray method

You can convert the DOM elements in jQuery by using the following method

$('.icons').toArray();

To achieve the same thing in Javascript you can use the ES6 spread operator

const icons = [...document.querySelectorAll('.icons')];

This method is so neat, I just love to use it!

Conclusion

Uhhh, this was a long one! 😀 The topic is never ending but as you can see all these things while you can do them with jQuery, you can easily achieve the same thing just with our good old JS! As I said at the beginning of the post I have huge respect for jQuery developers, but I am not finding it useful anymore. Maybe I didn’t use it that much in-depth, but even if I need something in-depth I would choose React or Vue to get the job done.

Anyway, I hope you enjoyed the post and that you will get something useful out of this post. If you did, please let me know in the comments section below! Share this post if you got some value from it. Thanks for reading! Gotta give the credit to the you might not need jQuery, they’ve done a great job!

What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top