Native JavaScript Equivalents of jQuery Methods: Events, Ajax and Utilities

Share this article

This is the final part of my series which follows on from Do You Really Need jQuery?
In this article, we’ll look at JavaScript equivalents for the more advanced methods jQuery provides…

Launching Scripts on Page Load

In the dim and distant past, developers would place scripts in the HTML head and use window.onload = start; to launch an initial function. It worked but window.onload only fires after all embedded files such images have been fully downloaded; you might be waiting some time for code to run. jQuery provides a far more efficient method:
$(start)
The start() function is executed as soon as the HTML has downloaded and the DOM is ready, but it won’t wait for other assets. Behind the scenes, it uses the native DOMContentLoaded event with fallbacks in jQuery 1.x for IE6/7/8:
document.addEventListener("DOMContentLoaded", start);
I used to fret about this sort of nonsense. It’s unnecessary: simply load your script at the bottom of the page just before the closing </body> tag and you’ll know the DOM is ready.

forEach

jQuery allows you to run a custom function on all items in an array. (This includes collections of nodes. Although these may start life as a NodeList, jQuery copies them to an array-like object before they’re returned):
$("p").each(function(i) {
	console.log("index " + i + ": " + this);
});
each is used internally when you apply multiple methods to the jQuery chain. This command would loop all <p> nodes twice:
$("p").addClass("newclass").css({color:"#f00"});
The native forEach is supported in most browsers including IE9+. However, it only applies to arrays so we need to convert NodeLists by looping through all items or using the Array slice prototype:
Array.prototype.slice.call(document.getElementsByTagName("p"));
Ughh. Personally, I prefer a short custom function which can be passed an array, NodeList or object with a callback. It iterates through the items passing each with its index to that function. This example automatically cancels further processing the first time the callback returns false:
function Each(obj, fn) {
	if (obj.length) for (var i = 0, ol = obj.length, v = obj[0]; i < ol && fn(v, i) !== false; v = obj[++i]);
	else for (var p in obj) if (fn(obj[p], p) === false) break;
};

Events

Event handling was awful in the pre-jQuery days. IE6/7/8 implemented a different event model and even those browsers which supposedly followed W3C standards had enough inconsistencies to make development awkward. jQuery still makes events easier to comprehend:
$("#clickme").on("click", function(e) {
	console.log("you clicked " + e.target);
	e.preventDefault();
});
But the native equivalent isn’t too difficult:
document.getElementById("clickme").addEventListener("click", function(e) {
	console.log("you clicked " + e.target);
	e.preventDefault();
});
This won’t work in IE6/7/8 but nor will jQuery 2.x. Most libraries provide a workaround which registers events using the oldIE attachEvent method. Alternatively, if you only require one event of a specific type on a node, simply apply the cross-browser DOM1 ‘on’ methods, e.g.
document.getElementById("clickme").onclick = runSomething;
(Don’t forget to include a line such as e = e ? e : window.event; at the top of your handler function to cope with the oldIE event object). Remember, none of this is required if you’re supporting IE9+. jQuery provides non-standard types such as ‘focusin’ and ‘live’ events, i.e. matching elements added to the page by future operations will also have the event applied. jQuery achieves this by attaching a handler to a parent element (such as the page body) and analyzing the event object as it bubbles up through the DOM. You can do this yourself — it’s more efficient, uses less code and is standard JavaScript practice, e.g. rather than attaching a hover event to every table row, you attach it to the table, analyze the object and react accordingly. If you prefer jQuery’s syntax, why not use Remy Sharp’s min.js? It provides the $ selector, chained on events, trigger functionality and forEach support. The total weight: 617 characters for the minified version.

Ajax

When was the last time you developed a project which required XMLHttpRequest, script injection, GET requests, POST submissions, JSON handling and image loading? jQuery handles many situations and, while it’s flexible, you’ll rarely require all those options. Typical jQuery Ajax code:
$.ajax({
	url: "webservice",
	type: "POST",
	data: "a=1&b=2&c=3",
	success: function(d) {
		console.log(d);
	}
});
The native equivalent:
var r = new XMLHttpRequest(); 
r.open("POST", "webservice", true);
r.onreadystatechange = function () {
	if (r.readyState != 4 || r.status != 200) return; 
	console.log(r.responseText);
};
r.send("a=1&b=2&c=3");
There are more options to consider — such as timeouts — so I would suggest wrapping native code in an easy-to-use function. However, you can optimize it for your project and implement some of the nicer XMLHttpRequest2 features such as binary data, upload progress and cross-origin requests which jQuery doesn’t (directly) implement.

Should You Use jQuery?

Only you can make that decision but using jQuery as a default starting point for every project will not necessarily be efficient or lead to elegant code. jQuery has been immensely useful and was one of the primary reasons for the rebirth of front-end development. However, unlike specialist libraries for handling canvas, SVGs or other focused tasks, jQuery provides a generic set of tools — you’ll never need them all. The browser vendors have caught up and, unless you need to support oldIEs, jQuery is not the essential resource it once was. To put this it context, if you’ve migrated to jQuery 2.0 you probably don’t need jQuery. I’ll leave you with a link to Vanilla JS; a library used by many of the top web companies which has a modular architecture and is smaller than all its competitors. The site is tongue-in-cheek but illustrates the point beautifully.

Frequently Asked Questions (FAQs) about jQuery vs Raw JavaScript

What are the main differences between jQuery and raw JavaScript in terms of syntax?

jQuery is essentially a JavaScript library, which means it’s built on top of raw JavaScript. The syntax of jQuery is designed to make it easier to navigate a document, create animations, handle events, and develop Ajax applications. On the other hand, raw JavaScript has a more complex syntax that requires a deeper understanding of the language. However, it provides more control and flexibility to the developer.

Why would I choose jQuery over raw JavaScript for event handling?

jQuery simplifies event handling by providing methods that work across different browsers. It offers functions like .on() and .click() that make it easy to attach event handlers to elements. In raw JavaScript, you would need to use addEventListener, which can be more complex and doesn’t have the same level of browser compatibility.

How does Ajax implementation differ between jQuery and raw JavaScript?

jQuery provides a high-level interface for Ajax functionality, making it easier to use and manage. It offers methods like .ajax() and .get() that handle the complexities of Ajax requests. In contrast, raw JavaScript requires a more detailed understanding of the XMLHttpRequest object, which can be more complex and time-consuming.

Can I use jQuery functions in raw JavaScript code?

Yes, you can use jQuery functions in raw JavaScript code because jQuery is a library built on JavaScript. However, you need to include the jQuery library in your project before you can use its functions.

Is jQuery slower than raw JavaScript?

jQuery can be slower than raw JavaScript because it’s a library and has additional overhead. However, the difference in performance is often negligible and may not be noticeable in most applications. The ease of use and cross-browser compatibility provided by jQuery often outweighs the slight performance cost.

Is jQuery still relevant with the advent of modern JavaScript frameworks?

While modern JavaScript frameworks like React, Angular, and Vue.js offer more features and are more suitable for building complex applications, jQuery is still relevant for simpler tasks. It’s lightweight, easy to learn, and has a large community and plenty of resources.

What are the advantages of using raw JavaScript over jQuery?

Raw JavaScript provides more control and flexibility to the developer. It doesn’t have the overhead of a library, so it can be faster. It’s also a fundamental web technology, so understanding it is crucial for any web developer.

How does browser compatibility compare between jQuery and raw JavaScript?

jQuery is designed to smooth out the differences between browsers, making your code more portable. Raw JavaScript can have cross-browser compatibility issues, requiring more effort to ensure your code works on all browsers.

Can I mix jQuery and raw JavaScript in the same project?

Yes, you can mix jQuery and raw JavaScript in the same project. In fact, it’s common to use jQuery for simpler tasks and raw JavaScript for more complex or performance-critical tasks.

Do I need to learn raw JavaScript before learning jQuery?

While it’s possible to learn jQuery without knowing raw JavaScript, it’s generally recommended to have a basic understanding of JavaScript first. This will make it easier to understand what jQuery is doing and how to use it effectively.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

HTML5 Dev CenterJavaScriptjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form