DEV Community

Cover image for What is jQuery? Learn one of the most popular JavaScript libraries
Hunter Johnson for Educative

Posted on • Originally published at educative.io

What is jQuery? Learn one of the most popular JavaScript libraries

As web developers, we encounter HTML, CSS, and JavaScript fairly early on. As our pages become more complex, the JavaScript required gets more complex to write. That's where libraries come in. A JavaScript library is a file that contains functions for accomplishing common tasks, reusing code, and simplifying your JavaScript code overall.

jQuery is one of the most popular JavaScript libraries out there. jQuery makes web development easier by overcoming all the “stuff” that makes JavaScript difficult to use. With jQuery, you can call simple methods instead of rewriting task blocks.

Any web developer should have jQuery under their belt. So today, we will introduce you to the library and show you how to get started.

Today, we will cover:

What is jQuery?

jQuery is a lightweight, open-source JavaScript library that helps us build interactive web pages with animations, visual effects, and advanced functionality. It is the most popular JavaScript library, used by around 70 million websites worldwide.

The jQuery motto is “write less, do more”, because it reduces many lines of raw JavaScript code into a single line with its simple interface. The main features of jQuery include:

  • Event Handling
  • DOM Manipulation
  • Animations and Effects
  • AJAX framework

Let's see how jQuery works to simplify our JavaScript code. Here is a popular manipulation method we use with vanilla JavaScript to load some paragraphs onto the DOM:

JavaScript:

// Updating the text present in 4 paragraph elements
document.addEventListener("DOMContentLoaded", function() {
   paragraphs = document.getElementsByTagName("p")
   for (i = 0; i <= paragraphs.length; i++) {
       paragraphs[i].innerHTML = "This is a Paragraph";
   }
});
Enter fullscreen mode Exit fullscreen mode

HTML:

<html>
<head>
</head>
<body>
  <div>
     <p>  </p>
     <p>  </p>
     <p>  </p>
     <p>  </p>
  <div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output:

This is a Paragraph

This is a Paragraph

This is a Paragraph

This is a Paragraph

See how it compares to some jQuery that produces the same results. The jQuery library uses JavaScript under the hood to make code more readable.

// Updating the text present in 4 paragraph elements
$(document).ready(function() {
   $("p").html("This is a Paragraph")
});
Enter fullscreen mode Exit fullscreen mode

Why learn jQuery?

The jQuery library is still one of the most popular libraries seen in legacy code. Its mantra of writing less to do more makes it still a popular library to continue to use today.

“Write less, do more.”

jQuery is probably the most popular and extendable JavaScript library. It is used by big companies like Netflix, Google, IBM, and Microsoft. It is the commonly the first library that JavaScript developers learn because:

  • Its syntax for AJAX calls is very simple compared to the native XmlHttpRequest
  • It offers shorthand solutions to common JavaScript challenges, like sorting and filtering arrays
  • Many other libraries have jQuery dependencies
  • It works on the server side of Node

Recent advancements in the frontend world with JavaScript frameworks like React and Angular and the fetch API make jQuery a little long in the tooth, but use cases still exist depending on what is needed for your project.

Bootstrap, for the time being, and WordPress use jQuery to build their components and themes. Many of the big tech companies, while they may not start green field projects with jQuery, still build on ones that started with jQuery. So, it’s a good idea to understand jQuery to have it on your resume.

jQuery syntax

The jQuery library is made up of selectors, event handlers, and DOM traversal helpers. Along with Ajax, jQuery does just about everything you need JavaScript to do for your web page. There are three most important elements that make jQuery work are:

  1. $() or jQuery(): the $() exists for the sole purpose of making it so you don’t have to write out jQuery() every single time you would like to use a selector.
  2. selector: this is how we select our DOM (Document Object Model) element. It’s the element we want to make changes to when the page loads.
  3. action(): this is the function that will tell the DOM what to do. It could be an event listener, or it could be an effect, depending on the use case.

Together, a simple jQuery statement is written as:

jQuery

The $() is preferable to the jQuery() simply because it’s more commonly used. However, both will work.

Brief introduction to the DOM

jQuery uses the Document Object Model (DOM) to manipulate, traverse, and select elements. The HTML document is loaded onto the DOM, where the browser creates a node tree when the page loads. A familial, hierarchical relationship is formed with the elements on the tree where elements are parents, children, and siblings of each other.

jQuery can then manipulate that object tree. We encapsulate all of our jQuery logic with the following selector:

$(document).ready(cb) //cb is a callback function
Enter fullscreen mode Exit fullscreen mode

As you can see, this selector is an instance of the $(selector).action() syntax we established above. The document on the window object is the selector and the action is the ready() method. This function will do all the logic that is inside the callback function that is passed as the argument to the method.

Here is a basic Hello World example of loading and manipulating the DOM with jQuery:

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
   </script>
</head>
<body>
  <div>
     <h1>  </h1>
  <div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(() => {
   $("h1").html("Hello World");
});
Enter fullscreen mode Exit fullscreen mode

Introducing Selectors

In the same way that CSS Selectors find HTML elements to apply a style, jQuery selectors find DOM elements to apply effects or events listeners. We use the $() function with a string passed in that identifies the specific element(s) in some way.

Some of the ways we can select elements:

  • Tag Name
  • Id
  • Class
  • Attribute
  • Child
  • Descendants

Select by Tag Name

When you select by tag name, use HTML tag names such as div or h1, as seen in the Hello World example above.

Select by Id

Use the familiar CSS syntax you use when selecting an element by id to grab a DOM element in jQuery:

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
   </script>
</head>
<body>
  <div id="logo">
     <img src="http://placekitten.com/300/300" alt="placekitten"/>
  <div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(() => {
      $('#logo').append('kittty catttt!'); //appending text to div element with id=logo
});
Enter fullscreen mode Exit fullscreen mode

In the code snippet, the text is only appended to the div with an id of logo.

Select by Class

As with CSS, we can also select elements by their class name. Use a ‘.’ in front of the class name to select this element:

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
   </script>
</head>
<body>
  <div id="logo">
        <p class="example-1"></p>
<p class="example-1"></p>
<p class="example-1"></p>
<p class="example-1"></p>
  <div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(() => {
      $('.example-1').append('this is a paragraph'); 
      //appending text to div element with class= “example-1”});
Enter fullscreen mode Exit fullscreen mode

In the code snippet, the text is appended to every element with a class of example-1.

Select by Attribute and Attribute Value

Selection by attribute and attribute value exists as well. Use square brackets [ ] to select those elements:

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
   </script>
</head>
<body>
  <div id="logo">
        <p class="example-1" id="red"></p>
<p class="example-1" id="blue"></p>
<p class="example-1" id="yellow"></p>
<p class="example-1" id="green"></p>
  <div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(function () {
   $('.example-1').append("This is a paragraph element'");
   $('[id = "red"]').css("color", "red");
   $('[id = "green"]').css("color", "green");
   $('[id = "yellow"]').css("color", "yellow");
   $('[id = "blue"]').css("color", "blue");
   $('[class]').css({"background":"lightgray", padding: '20px'});
});
Enter fullscreen mode Exit fullscreen mode

Create new Elements

Creating new elements in jQuery is as simple as using the $() function:

$(document).ready(function () {
   var newDiv  = $("<div>") // Create an empty div element
   var newListItem = $("<li> ab </li>") // Create list element with content "ab"
});
Enter fullscreen mode Exit fullscreen mode

This only creates the element. It does not add it to the DOM. We need to do a separate action for adding it to the web page.

Actions/Event Handler

At a high level, an action or an event handler is a function that is triggered by a user’s interaction with your web page. In jQuery, there are all kinds of events that can be used to trigger an event handler: mouse, keyboard, form, and more!

It is the responsibility of the event handler to listen for a particular event on a given element. As soon as the user interacts with that element, an event handler is fired that performs the logic in that function.

In jQuery, we use the familiar $(“selector”).action() syntax as the basis for our handler:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
  </script>
</head>
<body>
  <div>
    <button> Click Me </button>
  <div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(() => {
   $("button").click((event) => {
       alert("Button clicked by user!");
   });
});
Enter fullscreen mode Exit fullscreen mode

The selector is chosen as we have done before. The action is the actual event that we are listening for on the element that is selected. Here, the button tag is listening for a click event. When the button is clicked, it will alert the user.

Try logging into your console the event. The event object is full of different properties that could prove useful in your logic. This object is included by default to all event handlers.

How to install jQuery

To utilize jQuery, you need to have a link to the library in your project. There are three ways that you can do that.

1- Download a local copy of the jQuery library from their website into your project folder and link to it in the head of your HTML Document.

<head>
<script src="link-to-library"> </script>  
</head>
Enter fullscreen mode Exit fullscreen mode

2- If you are comfortable using npm or yarn with a package.json file, install the jQuery package:

// npm 
install jquery

//yarn
yarn add jquery
Enter fullscreen mode Exit fullscreen mode

3- Use a CDN (Content Delivery Network) to link to the jQuery library you’d like to use. Place the script in the head of your document.

<head>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>  
</head>
Enter fullscreen mode Exit fullscreen mode

Make your first jQuery application

Try your hand at setting up a simple jQuery application. If you get stuck, there is a solution provided to help guide your process.

We will take the first step to building a simple jQuery To Do list application. This portion of the program should assign a click event handler to the add button and generate an alert displaying the task added in the text box.

To add a task in our to-do list web page, the user enters a new task in a text box and then clicks on the add button. The task in this challenge is as follows:

  • Assign a click event handler to the add button with an id of addTask.
  • When the add button is clicked:
    • If the textbox is empty, generate an alert with the text “Error: Please enter a task before clicking the Add button”.
    • If the text box is not empty, generate an alert with the text containing the task name. For example, if the text in the input box is “Complete Assignment”, generate an alert with text “New Task: Complete Assignment”.
  • Clear the text inside the text box after the add button is clicked.

Note: The current value of the input box can be accessed using $("selector").val().

Additionally, the text present in the text box can be cleared out using $("selector").val("").

Sample Input: Enter “Complete Assignment” in the text box and click the add button.

Sample Output: An alert with the text “New Task: Complete Assignment” is generated and the text box is cleared out.

Check it out below and try solving it for yourself!

HTML:

<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
  </head>
  <body>
    <div class="container">
      <input type="text" class="textBox" placeholder="Enter task here">
      <button id="addTask" class="fa fa-plus">  </button>
      <div class = "notCompleted">
        <h3>To Do:</h3>
      </div>
      <div class="completed">
        <h3>Done:</h3>
      </div>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

JavaScript:

$(document).ready(function () {
    // code goes here
});
Enter fullscreen mode Exit fullscreen mode

Solution:

$(document).ready(function() {
    $("#addTask").click(function() { // click event handler
        if ($(".textBox").val() != "") {
            alert("New Task: " + $(".textBox").val());
            $(".textBox").val(""); // clear out the text box
        } else {
            alert("Error: Please enter a task before clicking the 'Add' button.");
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

Solution Review

Output:

Javascript

  • On line 2, we assign a click event handler to the button with the id addTask. The button class is already assigned in the web page HTML.
  • On line 3, we extract the current value of the text box with the class textBox using $(".textBox").val(). The text box class is also assigned in the web page HTML.
  • If the text box is not empty, we generate the alert with the task on line 4 and clear out the text box in line 5.
  • If the input box is empty, we generate the alert with the text “Error: Please enter a task before clicking the Add button” on line 8.

What to learn next

Congrats! You are now familiar with jQuery and have created your own first step to building a functioning application. Your next steps are:

  • Event bubbling
  • Traversing the DOM
  • Effects and animations
  • Callback functions
  • AJAX
  • GET vs POST methods

At this point, you are ready to tackle our course, The Complete Guide to jQuery. In this course, you will continue your jQuery journey with more event handling, animations, DOM traversal and manipulation, and AJAX methods. You will be working on an interactive project throughout the course, with quizzes and challenges at the end of each chapter.

Happy learning!

Continue reading about JavaScript

Start a discussion

What JavaScript tool is your favorite to use? Was this article helpful? Let us know in the comments below!

Top comments (0)