DEV Community

Cover image for What is jQuery Really? A Look Under the Hood
Garrin Costa, Jr.
Garrin Costa, Jr.

Posted on

What is jQuery Really? A Look Under the Hood

What is jQuery Really?

jQuery can drastically simplify and alleviate many headaches when working with HTML, CSS, and JavaScript. Taking a little time to understand how a tool works — the mechanism that drives it — is often the difference between having access to a tool and having command over it.

To better understand what jQuery is doing under the hood, it is helpful to understand a little bit about the DOM. The DOM (Document Object Model) is a programming interface, built by browsers, which represents the structure of a web document in memory. It is created when a webpage is loaded, representing the document with a tree-like structure. The DOM can be thought of like a bridge or a hub, allowing a webpage's content, styling, and interactivity to be accessed and manipulated dynamically.

A look under the hood — engine components exposed, illustrating the mechanism beneath the surface.
A look under the hood — engine components exposed, illustrating the mechanism beneath the surface.

The DOM Problem jQuery Solves

The DOM exposes a set of built-in browser APIs for accessing and manipulating elements. These APIs offer a world of capabilities and give us precise control, but they are verbose and low-level by design, requiring a lot of explicit instruction for even simple operations.

jQuery wraps those verbose native APIs in shorter, more readable methods. We write the jQuery shorthand — jQuery handles the verbose part under the hood.

The example below demonstrates a simple DOM interaction. We're going to grab a button on a webpage and change its color when clicked — the same operation written first in vanilla JavaScript, then in jQuery:

document.getElementById('button')
  .addEventListener('click', function() {
    this.style.backgroundColor = 'red';
  })
Enter fullscreen mode Exit fullscreen mode

As you might notice, the code needed to perform relatively simple modifications can get cumbersome. This is just ONE modification.

Now here's the same operation done with jQuery:

$('#button').click(function() {
  $(this).css('background-color', 'red');
})
Enter fullscreen mode Exit fullscreen mode

jQuery collapses our JavaScript into just a few lines of clean, readable code.

$ is Just a Function

As we pull back the curtain on jQuery, let's first look at the $ symbol.

A common misconception many beginners have about this is that $ is special syntax — something built into JavaScript itself. Perhaps assuming JavaScript just knows what $ means.

However, that is not the case. We know that $ is a valid character to use when naming variables in JavaScript, but that's all. On its own, $ means nothing to JavaScript unless defined — which is exactly what happens when jQuery is imported. Both jQuery and its alias $ are defined as the jQuery function. By convention, most developers use $, but either works — what matters is consistency.

We pass element selectors into the function as arguments. It returns an array-like container (the jQuery object) that contains the selected DOM nodes. This gives us access to jQuery's methods, which we can execute on the selected elements.

To get access to the jQuery library and use it in a project, you can download the library and then in your project's HTML file, create a script tag with a src attribute that points to your copy of jQuery:

<!-- Local download -->
<script src="jquery.js"></script>
Enter fullscreen mode Exit fullscreen mode

Another option is to load jQuery via CDN:

<!-- CDN -->
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

What You Actually Get Back

Unlike vanilla JavaScript which returns raw DOM elements directly, jQuery returns an array-like container holding the nodes. With jQuery, we manipulate elements through this container, not directly.

You can see what this looks like for yourself. Open your DevTools console on any jQuery page and run $('p'). What you get back should look something like this:

T {0: p, 1: p, 2: p, 3: p, 4: p, 5: p, 6: p, 7: p, 8: p, 9: p.copyright, 10: p, length: 11, prevObject: T}
Enter fullscreen mode Exit fullscreen mode

What you're seeing is the jQuery object. It contains indexed elements and a length — the number of matched elements — along with some internal jQuery properties (prevObject) that are beyond the scope of this article. If we expand it, we can see a vast array of methods and properties now accessible to us. This behavior of returning the jQuery object enables us to write the same code whether our selector matches one element or many — jQuery handles the iteration.

Vanilla JavaScript requires a manual loop:

var paragraphs = document.querySelectorAll('p');
for (var i = 0; i < paragraphs.length; i++) {
  paragraphs[i].style.color = 'red';
}
Enter fullscreen mode Exit fullscreen mode

Whereas jQuery silently iterates:

$('p').css('color', 'red');
Enter fullscreen mode Exit fullscreen mode

Much simpler in form, easy to follow, and easy to chain.

Why Chaining Works

When we call a jQuery function, what we get back is the jQuery object, rather than the raw node that we're operating on. This is by design. What's special about this behavior is that the jQuery object — that container that wraps our raw data — comes equipped with many of jQuery's built-in methods and properties. It gives us something to operate on. This is what makes chaining jQuery methods so simple and effective.

Why would we want to chain methods? What makes this so useful? Take a look at this example:

$('#button').css('background-color', 'red')
            .slideUp(500)
            .slideDown(500);
Enter fullscreen mode Exit fullscreen mode

Here, we've performed three different operations on our #button element without having to re-select it three times. It's simple, logical, and sleek.

Event Handling

Event handlers wait for a specific event and invoke a callback function when that event occurs. jQuery makes this operation concise and readable. With jQuery, .on() is the universal event handler. Though not the only way to implement event handling, it is preferred for flexibility and consistency. It looks like this:

$('#button').on('click', function() {
  // do something
});
Enter fullscreen mode Exit fullscreen mode

jQuery also provides shorthand methods for specific event types — here are a few common ones.

Let's say we have some card elements on our page and we want to blur the background when we hover on a card. This requires a couple of functions. In jQuery, we can do this like so:

$('#card').hover(
  function() {
    $(this).addClass('expanded');
    $('body').addClass('blurred');
  },
  function() {
    $(this).removeClass('expanded');
    $('body').removeClass('blurred');
  }
);
Enter fullscreen mode Exit fullscreen mode

Our $ is a function, into which we pass the #card element selector. Since jQuery returns its container object, we can then chain .hover() to the object and pass the functions that will perform our desired action. Those functions can also call the jQuery object to do so.

Here's an example of showing/hiding options based on checkbox state:

$('#checkbox').change(function() {
  $('#options-list').toggle();
});
Enter fullscreen mode Exit fullscreen mode

We start with calling $ and pass into it the #checkbox selector. We implement the .change() jQuery method on the returned object, letting us pass a callback function which passes another $ call with our next element selector as its argument, returning the jQuery object onto which we can apply the .toggle() method. Clean and concise.

And here's one more example showing how we might use jQuery to implement an event listener that starts music playback on spacebar press:

$(document).keydown(function(e) {
  if (e.key === ' ') {
    music.play();
  }
});
Enter fullscreen mode Exit fullscreen mode

This again shows how simple and readable our code can be when implementing operations that often prove tedious and difficult to follow otherwise.

Conclusion

I hope this has helped in showing some of jQuery's capabilities and usefulness, as well as given some insight into what's going on under the hood. A deeper understanding of how jQuery interacts with our code makes bugs easier to avoid — and when they do occur, easier to debug. It also deepens our understanding of JavaScript as a whole.

Another benefit to understanding a library like this is that it can serve as a template for understanding ANY library. While syntax, structure, and individual details will vary, the broader concepts often overlap. This can make expanding our range of knowledge and broadening our toolsets a much less daunting and more rewarding experience.

Top comments (0)