- What is jQuery?
- How to use jQuery to Interact with the DOM
CDNContent Delivery Network
MinifiedA file that the browser can still interpret correctly, but has none of the bits helpful to humans. Used to reduce the size of a file
CSS SelectorA description of how to find an element on the page
Loading the jQuery library
To use the jQuery library, you’ll need to include the following lines in your HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="path/to/your/jquery.min.js"><\/script>')</script>
Let’s talk about what’s going on here:
In the first line, we’re linking to the Google-hosted CDN (Content Delivery Network) for jQuery. Both Google and Microsoft host the jQuery library, and for our purposes we’ll go ahead and stick with the Google link. In this link, we can see which version of jQuery we’re using, which is
3.4.1 (as of the writing of this lesson).
In the second line, we’re including a link to a local set of jQuery files that we’ve downloaded to our machine and included in the directory for our project. This line isn’t strictly required for us to use jQuery, but rather is a fallback to make sure that we can still access the library in the event that we are unable to access the CDN for some reason (better safe than sorry, right?). You can download a copy of jQuery here. Note: be sure to download the same version that you’re referencing in the Google CDN link.
Note: If you look at the file extension you’ll see the file says
jquery.min.js - that
min extensions indicates that its a
minified version of the jQuery library. jQuery is a large library, and in order to maximize performance (especially on larger code bases), reducing how much space your code takes up is incredibly important. A minified file indicates that it has been abbreviated using one of many different encryption techniques. You can read more about it in this Wikipedia article if you are interested in the what and why of minification.
First Lines of jQuery
Let’s say that we have a page with the following markup:
<h1 class="important-header">Dinosaurs are awesome.</h1>
Think about how you would use
document.querySelector('h1').innerText = 'I AM A DINOSAUR.'
Now, take a look at the same line of code in jQuery:
$('h1').text('I AM A DINOSAUR.');
Play around with the following example using jQuery.
- Change the replacement text to something else.
- Change the
- Add the following line of code:
- Change the text of an
h1element to “I’m learning jQuery!”.
- Select an element with a class of
Responding to User Events
This is the crux of front-end engineering. We present a user interface and then as the user interacts with the UI, we change and update what the user sees.
Let’s take a look at the jQuery syntax and then we’ll talk about what’s happening.
The following things are happening in the example above:
- We’re querying for any elements with the class of
- We’re adding an “event listener” to those elements. (There is just one in this case.)
- We’re listening for a user’s mouse click.
- We’re providing an anonymous function.
- In this example, the function will change the content of our heading.
Now, when a user clicks on that button. The browser will run the function we provided to the event listener!
For a list of other events other than click, look at the jQuery documentation.
- Write out event listener for a
Try It: Adding a CSS Class
Open the example below in CodePen using the “Edit on CodePen.”
We’re using a jQuery method called
toggleClass(). When the user clicks on the button, it either adds or remove the class
upside-down depending on whether or not it was already there.
- Can you create some additional CSS classes and toggle them?
- Can you also change the text?
- Is there anything like
Getting Values from the User
We’re getting somewhere! We can respond to actions and change elements. It would be cool if we could also get some information from the user. If you recall, HTML provides
<input> elements for just this kind of situation. jQuery helps out by providing the
.val() method for getting the value out of a selected
Let’s explore the following example.
In this example, we’re doing the following:
- We’re adding an event listener to the “Change Me” button.
- When it’s clicked, we’re grabbed the value of the input field and storing it into a variable.
- We’re then updating the contents of the
<h1>to the value we stored from the input field.
Try It: Secret Passcode Time
Can you change the code above so that it’s looking for a secret passcode before it prints a hidden message to the screen? It’s totally your call on what the password is and what the message should be. I don’t want to steal your creative thunder.
Knowing Which Element We Clicked!
Consider a situation where we have three boxes. When that particular box is clicked, we want to toggle a class on that box only. How do we know which box was clicked?
The callback function takes in an event argument. We can use this to determine the event target (what you clicked on).
Let’s take a look at the example below:
Can you create a class that adds a border and then toggle that class on the specific box that is hovered over? (For your own sanity, you probably want to remove the alert!)
Traversing the DOM
A little while ago, we wanted to figure out how to tell which element we clicked. But, what if we wanted to find an element in relation to the element we clicked? jQuery lets us navigate from one element to another. When the browser parses our HTML, it creates a big tree-like structure. jQuery lets us hop from branch to branch.
Let’s work through a box example again.
We want each box to have a button inside of it. When the user clicks the button, it should rotate the entire box. (We’re rotating the box with a CSS class called
This code does not work the way we’d like - right now when we click on the button, the button itself is rotating instead of the entire box. What we need to do is when the user clicks on a button, go up and find the box that it lives in (the parent element) and add the class to that element. We can use traversal like this:
You can see all of ways we can move around the DOM tree in jQuery documentation.
A Deeper Dive
Let’s take a closer look at how we can use the jQuery library!
Part One: Selectors
Out of the box, jQuery supports the selector syntax from CSS to find elements on the page just like
document.querySelectorAll from vanilla JS. So, you’ve already come pre-equipped with a bunch of knowledge for finding elements.
That said, let’s review some of the different ways we can find an element on page:
$('p'), selects all of a given element.
$('#heading'), selects the element with a given id.
$('.important'), selects all of the elements with a given class.
You can also use multiple selectors in the same statement:
$('p, #heading, .important'), selects everything listed above.
There are a few different ways to chain selectors to use them together. You can seperate these selectors with a comma, a space, or nothing at all.
$('p, #heading, .important')just combines all of the selectors together.
$('p #heading .important')treats each selector as a child of the previous. This will give you items of the class
importantthat are children of the id
headingwhich are inside a
$('p#heading.important')matches elements that have all three selectors. This selector would select a paragraph which was defined like this:
<p id="heading" class="important">
On top of querying for types of elements, classes, and ids, we can also search for elements by the type of attributes that it has.
Here are some examples:
$('input[type="date"]')will get all of the date selector inputs.
$('input[type="number"]')will get all of the number inputs.
$('input[type="submit"]')will get all of the form submission buttons.
See the API documentation here.
It’s not uncommon that you might want to go look for all of the “checked” elements. This includes drop downs, checkboxes, and radio buttons.
$('input:checked')will return all of the checked checkboxes.
$('input[type="radio"]:checked')will return all of the checked radio buttons.
Let’s take a look at this simple form and try out some selectors.
- Can you find all of the check boxes?
- Can you find all of the radio buttons?
- Can you find all of the checked elements?
- What about all of the checked checkboxes?
Use Chrome Developer Tools to select the form fields above. When properly selected you should see an array of selected elements. You should see sections of the page highlighted when you hover over the elements in the array.
Here is an little experiment where you can play around and try out some different selectors. This has some nice visual cues and allows you to toggle multiple selectors.
Exercise, Part One: The Presidents
For this exercise, we’re going to play with a table of the Presidents of the United States of America.
Let’s try out a few things, just to get our hands dirty. We’ll use the console in the Chrome developer tools to validate our work.
- Select each
- Select the first
- Select the third
- Select all of the elements with the class of
- Select all of the elements with either the class of
- Select all of the checked—umm—checkboxes. (You’ll probably want to check some checkboxes first.)
- Select all of the
tdelements with the class of
numberthat appear in a row of a
trwith the class of
Part Two: Manipulating CSS
Once we have an element in our sites, we probably want to do something with it, right?
In this case, let’s add some CSS styling. We can add and remove classes pretty easily in jQuery.
Keeping track of state is hard. jQuery is here to help. What if we were in a position where we want to add a class if an element had it, but remove it if it didn’t? jQuery’s
hasClass method is certainly helpful in this case.
$('.federalist').hasClass('federalist'); // Returns true, obviously.
But, it seems like this is a common pattern and there should be a better way to do this, right?
The other option is to use
toggleClass, which will either add or remove the class depending on whether or not the class currently exists.
(Do this like 17 times for good measure.)
Exercise, Part Two: Style the Presidents
- Add the class of
redto all of the Republicans.
- Add the class of
blueto all of the Democrats.
- Add the class of
yellowto the term column of the table.
- Take all the whig presidents and give them a purple background and white text.
Part Three: Filtering and Traversal
Let’s talk about a few DOM traversal methods.
Here are some of the all-stars of the DOM traversing world:
parent() method will take the currently selected element and go one level up the DOM tree.
This one will include all of the parents—all the way up to the
<body> of the page. Additionally, you can pass it a selector.
$('.some-selector').parents('.active') will traverse up the DOM, but only return the elements with the class of
This method returns all of the direct childen of the given selection. It will not search their children. Like
children() will also take a selector.
$('.some-selector').children('.active') will go through the children of the current query and only return the elements with the class of
siblings() will select all of the sibling elements based on the current query. Like its friends, it will also take a selector if you’re polite.
One you have queried for some elements using jQuery, you can use
find() to drill down a little deeper.
It’s useful to think of
find() as a more powerful alternative for
children() method will look only one level down the tree.
find() will search the children, the grandchildren, the great-grandchildren, and so on. The method will look at anything you currently have selected and then search within those results.
Which one do you use? It depends, do you want to traverse all the way down the tree or just down one level.
Exercise, Part Three: One-Term Presidents
- Add the
greenclass to anyone who served right after a president who died.
- Find all of the presidents who only served one term and add the class
- Add the class of
blueto the parent of a checked checkbox.
- Add the class of
yellowto the siblings of the parent (
td, in this case) of an unchecked checkbox.
Part Four: Adding to the DOM
Let’s take a look at some approaches of changing content in the DOM.
text() is like using
textContent. There is an important difference. The vanilla DOM manipulation tools allow you to assign the new value to
innerText. The jQuery methods on the other hand must be passed the new value as an argument.
Let’s compare and contrast.
var header = document.querySelector('h1'); var $header = $('h1'); header.innerText = 'New Header Text'; $header.text('New Header Text');
html() is to
innerHTML is to
innerText. Basically, change the HTML contents of a bigger element, not just the text of it. As a fun experiment, select an element and try to replace the contents to
<script>alert('YOU ARE HACKED!');</script> using both
html(). Let me know how it goes for you.
html() replaces the entire contents of an element.
append() adds new content onto the end of it.
html() replaces the entire contents of an element.
prepend() adds new content onto the beginning of it.
In order to take both
prepend() for a spin, let’s try the following code in the exercise below.
Exercise, Part Four: Dead Presidents
- Find all of the presidents who died in office (hint: they have a
diedclass on their
<span class="died">(Died)<span>to the the
- Bonus: Add a radio button before the number in each row.