jQuery vs Plain Old JavaScript (Vanilla JS)

Here's a quick and simple comparison of jQuery and plain old JavaScript (aka Vanilla JS). Before diving in, it's important to understand the jQuery function, which looks like this: $( ). When you pass in a query selector as the parameter, like so:

var $div = $("#someDiv");

The function returns a jQuery object that represents the div (when I assign a jQuery object to a variable, I like to prefix the variable name with a dollar sign so that I can easily recognize jQuery objects in my code). This object not only includes the real DOM object (which is a div in this case), it also includes many other methods that get added to it by jQuery. So a jQuery object is like a DOM object on steriods. For example, you can invoke the animate() method to easily animate the div like this:


If you've ever tried to write code to animate DOM objects, then you know how difficult it can be to do it right. jQuery makes it about as easy as possible.

For the rest of this article, let's assume that our HTML code looks like this:

<ul id="animal-list">
    <li id="dog">Dog</li>

And we'll assume that this is the CSS code:

.blue{ background-color: blue; }
.yellow{ background-color: yellow; }
.red{ background-color: red; }

Waiting For The Page To Load Before Executing JavaScript Code

In plain old JavaScript, you do this to wait for the page to load:

window.addEventListener("load", function(){
    // All your JS code goes here

In jQuery, you pass a function into the jQuery function like this:

    // All your JS/jQuery code goes here        

Creating and Appending Elements to the DOM

Plain old JavaScript:

let li = document.createElement("li");
li.innerHTML = "Mouse";
let list = document.querySelector("#animal-list");


let $li = $("<li>");
let $list = $("#animal-list");

Getting and Setting Attributes

Plain old JavaScript:

let dogLi = document.querySelector("#dog");
let id = dogLi.getAttribute("id"); // gets the 'id' attribute
dogLi.setAttribute("class", "yellow"); // sets the 'class' attribute


let $dogLi = $("#dog");
let $id = $dogLi.attr("id"); // gets the 'id' attribute
$dogLi.attr("class", "blue"); // sets the 'class' attribute

Selecting and Looping Through a Collection of Elements

Plain old JavaScript:

// DOM
let allListItems = list.querySelectorAll("li");
allListItems.forEach(function(li, index){
    li.setAttribute("class", "yellow")


let $allListItems = $list.find("li");
$allListItems.each(function($index, li){
    // Note that the li variable is NOT a jQuery object, so you can't use any jQuery methods on it
    // But you can turn it into a jQuery object like this:
    let $li = $(li);
    $li.attr("class", "blue");

Event Handling

Plain old JavaScript:

list.addEventListener("click", function(evt){
    evt.target.setAttribute("class", "red");


$list.on("click", function(evt){
    let target = $(evt.target);
    target.attr("class", "blue");